Categories
React Answers

How to use react-datepicker with React hooks forms?

Sometimes, we want to use react-datepicker with React hooks forms.

In this article, we’ll look at how to use react-datepicker with React hooks forms.

How to use react-datepicker with React hooks forms?

To use react-datepicker with React hooks forms, we can wrap it in the Controller component.

For instance, we write:

import React from "react";
import { Controller, useForm } from "react-hook-form";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function App() {
  const {
    handleSubmit,
    watch,
    control,
    formState: { errors }
  } = useForm();
  const onSubmit = (data) => console.log(data);

  console.log(watch("dateInput"));

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <Controller
        control={control}
        name="dateInput"
        render={({ field }) => (
          <DatePicker
            placeholderText="Select date"
            onChange={(date) => field.onChange(date)}
            selected={field.value}
          />
        )}
      />
      {errors.dateInput && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}

We call the useForm hook to return an object with various properties we use to add the date picker into the form.

Next, we add the Controller component in the form.

We set the control prop to control and we set the render prop to a function that renders the DatePicker component.

Then we set onChange to a function that calls field.onChange to set the value of the date picker.

And we render the value by setting the selected prop to field.value.

Conclusion

To use react-datepicker with React hooks forms, we can wrap it in the Controller component.

Categories
React Answers

How to map only a portion of an array with React?

Sometimes, we want to map only a portion of an array with React.

In this article, we’ll look at how to map only a portion of an array with React.

How to map only a portion of an array with React?

To map only a portion of an array with React, we can use the JavaScript array’s slice method.

For instance, we write:

import React, { useState } from "react";

const items = ["Item A", "Item B", "Item C", "Item D"];

export default function App() {
  const [showMore, setShowMore] = useState();

  return (
    <div>
      <button onClick={() => setShowMore((s) => !s)}>toggle show more</button>
      {showMore
        ? items.map((it) => <p key={it}>{it}</p>)
        : items.slice(0, 2).map((it) => <p key={it}>{it}</p>)}
    </div>
  );
}

We have a button that toggles the showMore state when it’s clicked.

If showMore is true, then we call items.map with a callback to render all the content of items in their own p elements.

Otherwise, we call slice with 0 and 2 to only return an array with the first 2 elements.

And we call map with a callback to render each item.

Therefore, when we click toggle show more, we should see the list toggle between 2 and 4 items.

Conclusion

To map only a portion of an array with React, we can use the JavaScript array’s slice method.

Categories
React Answers

How to add a background video with React?

To add a background video with React, we can add the loop, autoPlay and muted props to the video element.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <div>
      <video autoPlay loop muted>
        <source
          src="https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4"
          type="video/mp4"
        />
      </video>
    </div>
  );
}

We have autoPlay loop muted added to the video element so that the video plays automatically, repeats when it finishes playing, and it’s muted respectively.

In it, we add the source element with the src attribute set to the URL of the video we want to play in the background.

We add the loop prop to make it restart when the video is finished playing.

The muted prop mutes the video.

As a result, we have a video that loops forever silently on the page.

Categories
React Answers

How to set selected value of a select drop down to null with React?

Sometimes, we want to set selected value of a select drop down to null with React.

In this article, we’ll look at how to set selected value of a select drop down to null with React.

How to set selected value of a select drop down to null with React?

To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [selected, setSelected] = useState(null);

  return (
    <div>
      <select
        onChange={(e) => setSelected(e.target.value || null)}
        value={selected || ""}
      >
        <option value=""></option>
        <option value="1">cook dinner</option>
        <option value="2">do dishes</option>
        <option value="3">walk dog</option>
      </select>
    </div>
  );
}

to set onChange to a function that calls setSelected to e.target.value which is the selected value if it’s truthy.

Otherwise, we set it to null.

Next, we set the value prop to selected if it’s truthy and an empty string otherwise.

Since null is falsy, value will be an empty string if selected is null, which matches the value attribute of the first choice.

As a result, when we select the first choice, the empty option will be displayed.

Conclusion

To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null.

Categories
React Answers

How to retrieve dynamic child key upon emission of an event with React?

Sometimes, we want to retrieve dynamic child key upon emission of an event with React.

In this article, we’ll look at how to retrieve dynamic child key upon emission of an event with React.

How to retrieve dynamic child key upon emission of an event with React?

To retrieve dynamic child key upon emission of an event with React, we can store the key as a data- attribute.

Then we can get the data- attribute value from the dataset property.

For instance, we write:

import React from "react";

const ChildComponent = ({ changeCallback, dataKey }) => {
  return (
    <div>
      <input type="text" onChange={changeCallback} data-key={dataKey} />
    </div>
  );
};

export default function App() {
  const changeCallback = (evt) => {
    console.log(evt.target.dataset.key);
  };

  return (
    <div>
      <ChildComponent changeCallback={changeCallback} dataKey="abc" />
    </div>
  );
}

We create the ChildComponent component that renders an input element with the data-key attribute set to the dataKey prop’s value.

Also, set set the onChange prop of the input to changeCallback.

Next, we define changeCallback in App that gets the data-key attribute value with evt.target.dataset.key.

We render ChildComponent with changeCallback and dataKey set so that when we type in the input, we see the data-key attribute value logged.

Cobnclusion

To retrieve dynamic child key upon emission of an event with React, we can store the key as a data- attribute.

Then we can get the data- attribute value from the dataset property.