loading

how to set object key in useState, react state hook with the object and array

To update an object key in the state select the key and assign its value to that state

for example, if we have an object of books and we want to update the physics book name then we can do it in the following way

react hooks usestsate with object and array
react hooks usestsate with object and array

Preserve previous value

use the spread operator(…) to preserve the previous value and only update the particular key so that no other keys override

Update the object key

{…prev, key: value} in object literal preserve the object’s previous value and update the desired key

import { useState } from "react";

const demo = () => {
  const [books, setBooks] = useState({
    physics: "",
    chemistry: "",
    math: "",
  });
  return (
    <div>
      <p>List of books</p>
      <form>
        <input
          type="subject"
          name="book"
          onClick={(e) =>
            setBooks((prev) => ({
              ...prev,
              physics: e.target.value,
            }))
          }
        />
        <button>Update book</button>
      </form>
    </div>
  );
};

export default demo;

how to update array object key in useState

In the same, we can also update the array but in the array, we will have to map to preserve other items of the array and use a filter to update that particular item of the array.

import { useState } from "react";

const demo = () => {
  const [faq, setFaq] = useState([
    {
      que: "",
      ans: "",
    },
  ]);
  return (
    <div>
      <p>List of books</p>
      <form>
        <input
          type="subject"
          name="que"
          onClick={(e) =>
            setFaq((prev) =>
              prev.map((el, index) => {
                if (index == i) {
                  return {
                    ...el,
                    que: e.target.value,
                  };
                }
              })
            )
          }
        />
        <textarea
          name="ans"
          onClick={(e) =>
            setFaq((prev) =>
              prev.map((el, index) => {
                if (index == i) {
                  return {
                    ...el,
                    ans: e.target.value,
                  };
                }
              })
            )
          }
        />
        <button>Update book</button>
      </form>
    </div>
  );
};

export default demo;

How to update the nested objects in useState

sometimes we are required to use nested objects in useState, in that case, it becomes difficult to update a key of an object in the useState set method. So let’s see how to update the nested object in usetstate.

  const [data, setdata] = useState({
    width: "160",
    text: "button",
    padding: "17",
    border: {
      width: "1",
      type: "solid",
      color: "red",
      radius: "20",
    },

    background: {
      isSolid: true,
      color: "red",
      gradient: { bg1: "red", bg2: "blue", angle: "120" },
    },
    textShadow: {
      x: "1",
      y: "-1",
      blur: "1",
      color: "",
    },
  });

above useState object is nested in 3 levels.
here I am updating the blur key of textshadow object

<input type="range"
   onChange={(e) =>setdata((prev) => ({
                        ...prev,
                        textShadow: {
                          ...prev.textShadow,
                          blur: e.target.value,
                        },
                      }))
                    }
/>

About Author

x

Order for website design

Help :