Categories
React Answers

How to update states onChange in an array of objects in React Hooks?

Sometimes, we want to update states onChange in an array of objects in React Hooks.

In this article, we’ll look at how to update states onChange in an array of objects in React Hooks.

How to update states onChange in an array of objects in React Hooks?

To update states onChange in an array of objects in React Hooks, we can return a new array with the new input value.

For instance, we write

const Comp = () => {
  const [data, setData] = useState([
    {
      id: 1,
      name: "john",
      gender: "m",
    },
    {
      id: 2,
      name: "mary",
      gender: "f",
    },
  ]);

  const updateFieldChanged = (index) => (e) => {
    const newArr = data.map((item, i) => {
      if (index === i) {
        return { ...item, [e.target.name]: e.target.value };
      } else {
        return item;
      }
    });
    setData(newArr);
  };

  return (
    <>
      {data.map((datum, index) => {
        <li key={datum.name}>
          <input
            type="text"
            name="name"
            value={datum.name}
            onChange={updateFieldChanged(index)}
          />
        </li>;
      })}
    </>
  );
};

to define the data state with useState.

Then we define the updateFieldChanged function that calls data.map with a callback that checks if index is i.

If it is, then we return a new object with the existing properties of item.

And we add the [name] property and set it to the e.target.value input value.

Then we call setData with newArr to update the state to the array returned by map.

Finally, we render the li elements with the inputs inside.

And we set the onChange prop to the function returned by updateFieldChanged called with index.

Conclusion

To update states onChange in an array of objects in React Hooks, we can return a new array with the new input value.

Categories
React Answers

How to use ES6 import alias syntax for React components?

Sometimes, we want to use ES6 import alias syntax for React components.

In this article, we’ll look at how to use ES6 import alias syntax for React components.

How to use ES6 import alias syntax for React components?

To use ES6 import alias syntax for React components, we can use the as keyword.

For instance, we write

import { default as StyledLibrary } from "component-library";

to import a default export from the component-library module.

We add a default export with

export default StyledLibrary;

Conclusion

To use ES6 import alias syntax for React components, we can use the as keyword.

Categories
React Answers

How to update and merge state object using React useState hook?

Sometimes, we want to update and merge state object using React useState hook.

In this article, we’ll look at how to update and merge state object using React useState hook.

How to update and merge state object using React useState hook?

To update and merge state object using React useState hook, we can call the state setter function with a callback that returns the new object state value.

For instance, we write

const Comp = () => {
  const [state, setState] = useState({ fName: "", lName: "" });
  const handleChange = (e) => {
    const { name, value } = e.target;
    setState((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

  return (
    <>
      <input
        value={state.fName}
        type="text"
        onChange={handleChange}
        name="fName"
      />
      <input
        value={state.lName}
        type="text"
        onChange={handleChange}
        name="lName"
      />
    </>
  );
};

to define the handleChange in the Comp component that calls setState with a callback that return an object with the prevState properties and the new property values.

We set the onChange prop to handleChange to get the input value from e.target.value and the name attribute value of the input from e.target.name.

Conclusion

To update and merge state object using React useState hook, we can call the state setter function with a callback that returns the new object state value.

Categories
React Answers

How to add CSS pseudo elements in React?

Sometimes, we want to add CSS pseudo elements in React.

In this article, we’ll look at how to add CSS pseudo elements in React.

How to add CSS pseudo elements in React?

To add CSS pseudo elements in React, we add real elements.

For instance, we write

<div>
  <span>Something</span>
  <div
    style={{ position: "absolute", WebkitFilter: "blur(10px) saturate(2)" }}
  />
</div>

in our React component, which is equivalent to

<div class="something"><span>Something</span></div>
<style>
  .something::after {
    content: "";
    position: absolute;
    -webkit-filter: blur(10px) saturate(2);
  }
</style>

in regular HTML and CSS.

.something::after selects the div after the span in the React component.

-webkit-filter is replaced with WebkitFilter in React.

Conclusion

To add CSS pseudo elements in React, we add real elements.

Categories
React Answers

How to set multipart in Axios with React?

Sometimes, we want to set multipart in Axios with React.

In this article, we’ll look at how to set multipart in Axios with React.

How to set multipart in Axios with React?

To set multipart in Axios with React, we can submit a FormData object when making the request.

For instance, we write

const Comp = () => {
  const [file, setFile] = useState();

  const fileUpload = (file) => {
    const url = "http://example.com/file-upload";
    const formData = new FormData();
    formData.append("file", file);
    const config = {
      headers: {
        "content-type": "multipart/form-data",
      },
    };
    return post(url, formData, config);
  };

  const onFormSubmit = (e) => {
    e.preventDefault();
    const { data } = await fileUpload(file);
  };

  const onChange = (e) => {
    setFile(e.target.files[0]);
  };

  return (
    <form onSubmit={onFormSubmit}>
      <h1>File Upload</h1>
      <input type="file" onChange={onChange} />
      <button type="submit">Upload</button>
    </form>
  );
};

to create the Comp component.

In it, we define the file state with useState.

Then we define the fileUpload function that creates a FormData object.

Next, we add the file object into the FormData object with append.

And then we make the request with the Axios post method with the url, formData object and the config that has the headers that sets content-type header to multipart/form-data.

Next, we define the onFormSubmit function that calls preventDefauly to stop the default form submit behavior.

And then we call fileUpload to upload the file.

Finally, we render a form element with a file input in it.

When the file selection is changed, onChange is called.

And onFormSubmit is called when we click Upload.

Conclusion

To set multipart in Axios with React, we can submit a FormData object when making the request.