Categories
React Answers

How to use React-datepicker with a Formik form?

Sometimes, we want to use React-datepicker with a Formik form.

In this article, we’ll look at how to use React-datepicker with a Formik form.

How to use React-date picker with a Formik form?

To use React-date picker with a Formik form, we can create a date picker component that renders the React-datepicker component.

We use the useFormikContext hook to let us add form validation with Formik to the React-datepicker component.

For instance, we write:

import React from "react";
import { Formik, useField, useFormikContext } from "formik";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

const DatePickerField = ({ ...props }) => {
  const { setFieldValue } = useFormikContext();
  const [field] = useField(props);
  return (
    <DatePicker
      {...field}
      {...props}
      selected={(field.value && new Date(field.value)) || null}
      onChange={(val) => {
        setFieldValue(field.name, val);
      }}
    />
  );
};
export default function App() {
  return (
    <div>
      <Formik
        initialValues={{ date: "" }}
        onSubmit={(values, { setSubmitting }) => {
          setTimeout(() => {
            console.log(JSON.stringify(values, null, 2));
            setSubmitting(false);
          }, 500);
        }}
      >
        {(props) => {
          const { dirty, isSubmitting, handleSubmit, handleReset } = props;
          return (
            <form onSubmit={handleSubmit}>
              <DatePickerField name="date" />
              <button
                type="button"
                className="outline"
                onClick={handleReset}
                disabled={!dirty || isSubmitting}
              >
                Reset
              </button>
              <button type="submit" disabled={isSubmitting}>
                Submit
              </button>
            </form>
          );
        }}
      </Formik>
    </div>
  );
}

We define the DatePickerField component that takes the props from the props object.

In the component, we call useFormikContext to return an object with the setFieldValue method.

Then we call the useField hook with props to create the field object which we use to set the selected state and use the field.name property to get the field’s name.

We call setFieldValue to set the field’s value by passing in the field name string and the selected value.

Then to use DatePickerField in a Formik form, we put it inside the render prop’s return value.

useFormikContext and useField returned all the values required to let Formik handle value change and form validation.

We also set initialValues to an object with the name of the field as the property names.

And we set the name prop of DatePickerField to the same value as the property value so validation and the value can be set as the value of the property with the same name.

Conclusion

To use React-date picker with a Formik form, we can create a date picker component that renders the React-datepicker component.

We use the useFormikContext hook to let us add form validation with Formik to the React-datepicker component.

Categories
React Answers

How to add select option with object as the value attribute value with React?

Sometimes, we want to add select option with object as the value attribute value with React.

In this article, we’ll look at how to add select option with object as the value attribute value with React.

How to add select option with object as the value attribute value with React?

To add select option with object as the value attribute value with React, we can set the value attribute to the index and then select the object from the index from the options array.

For instance, we write:

import React, { useState } from "react";

const options = [{ name: "apple" }, { name: "orange" }, { name: "grape" }];

export default function App() {
  const [option, setOption] = useState({});
  console.log(option);

  const handleChange = (e) => {
    setOption(options[+e.target.value]);
  };

  return (
    <select onChange={handleChange}>
      {options.map((option, index) => (
        <option key={index} value={index}>
          {option.name}
        </option>
      ))}
    </select>
  );
}

We have an array of options that we render as options in the select drop down.

To do the rendering, we call options.map with a callback that returns the option elements.

We set the value attribute value to index so we can select the object from the list once we selected an option.

Next, we define the handleChange function that calls setOption with options[+e.target.value] to set option to the selected object from options.

e.target.value has the value attribute value of the option element selected.

Therefore, from the console log, we see the object that corresponds to the options we selected from the drop down.

Conclusion

To add select option with object as the value attribute value with React, we can set the value attribute to the index and then select the object from the index from the options array.

Categories
React Answers

How to add a header and footer into a layout component with React?

Sometimes, we want to add a header and footer into a layout component with React.

In this article, we’ll look at how to add a header and footer into a layout component with React.

How to add a header and footer into a layout component with React?

To add a header and footer into a layout component with React, we can add the header and footer into the layout component.

For instance, we write:

import React from "react";

const Header = () => <header>header</header>;

const Footer = () => <footer>footer</footer>;

const Layout = ({ children }) => {
  return (
    <div>
      <Header />
      {children}
      <Footer />
    </div>
  );
};

export default function App() {
  return <Layout>hello world</Layout>;
}

We define the Header and Footer components to render content for the header and footer of the layout respectively.

Then we define the Layout component to render the Header and Footer around the children prop.

children has the content between the opening and closing tags of Layout.

Therefore, we see:

header
hello world
footer

rendered on the screen.

Conclusion

To add a header and footer into a layout component with React, we can add the header and footer into the layout component.

Categories
React Answers

How to fix the throttle mousemove event keep throwing event.persist() error issue with React?

Sometimes, we want to fix the throttle mousemove event keep throwing event.persist() error issue with React.

In this article, we’ll look at how to fix the throttle mousemove event keep throwing event.persist() error issue with React.

How to fix the throttle mousemove event keep throwing event.persist() error issue with React?

To fix the throttle mousemove event keep throwing event.persist() error issue with React, we can use the throttle Lodash method with the event.persist method.

For instamce, we can write:

import React, { useMemo } from "react";
import { throttle } from "lodash";

export default function App() {
  const onMouseMove = useMemo(() => {
    const throttled = throttle((e) => console.log(e.screenX), 300);
    return (e) => {
      e.persist();
      return throttled(e);
    };
  }, []);

  return (
    <div>
      <div onMouseMove={onMouseMove}>Content</div>
    </div>
  );
}

to define the onMouseMove function that is defined by calling the useMemo hook with a function that does the throttling with Lodash throttle.

We throttle the (e) => console.log(e.screenX) to run once every 300 milliseconds.

Then we return a function that calls e.persist to persist the event.

And then we throttled mousemove event handler that we created with throttle by calling it with e.

Now when we move our move over the div, we should no longer see errors when calling event.persist.

Conclusion

To fix the throttle mousemove event keep throwing event.persist() error issue with React, we can use the throttle Lodash method with the event.persist method.

Categories
React Answers

How to turn off background hover for bar charts with Recharts?

Sometimes, we want to turn off background hover for bar charts with Recharts.

In this article, we’ll look at how to turn off background hover for bar charts with Recharts.

How to turn off background hover for bar charts with Recharts?

To turn off background hover for bar charts with Recharts, we can set the cursor prop of the Tooltip component to false.

For instance, we write:

import React from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend
} from "recharts";

const data = [
  { name: "Page A", uv: 4000, pv: 2400, amt: 2400 },
  { name: "Page B", uv: 3000, pv: 1398, amt: 2210 },
  { name: "Page C", uv: 2000, pv: 9800, amt: 2290 },
  { name: "Page D", uv: 2780, pv: 3908, amt: 2000 },
  { name: "Page E", uv: 1890, pv: 4800, amt: 2181 },
  { name: "Page F", uv: 2390, pv: 3800, amt: 2500 },
  { name: "Page G", uv: 3490, pv: 4300, amt: 2100 }
];

const SimpleBarChart = () => {
  return (
    <BarChart
      width={600}
      height={300}
      data={data}
      margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
    >
      <CartesianGrid strokeDasharray="3 3" />
      <XAxis dataKey="name" />
      <YAxis />
      <Tooltip cursor={false} />
      <Legend />
      <Bar dataKey="pv" fill="#8884d8" />
      <Bar dataKey="uv" fill="#82ca9d" />
    </BarChart>
  );
};

export default function App() {
  return <SimpleBarChart />;
}

We define the SimpleBarChart component that renders the BarChart component.

We set the data prop to data to render the data array’s entries in the bar chart.

And we render the x-axis with the XAxis component.

The dataKey prop is set to 'name' to take the name property of each entry as the x-axis values.

We add the bars with the Bar component and we set the dataKey prop to the name of the property with the values we want to render as the bar heights.

Finally, we add the Tooltip component to add the tooltips that are shown when we hover over each bar.

And we set the cursor prop to false to disable highlighting the background when we hover over a bar.

Conclusion

To turn off background hover for bar charts with Recharts, we can set the cursor prop of the Tooltip component to false.