Home > front end >  How can update the DOM if the state changes?
How can update the DOM if the state changes?

Time:05-19

I've created the box container dynamically according to the input changes.

  1. If I entered 1, it will create one box
  2. If I change the input lets say 2, its create 3 box but it should create 2
import React from 'react';
import './style.css';

export default function App() {
  const [value, setValue] = React.useState();
  const boxRef = React.useRef();

  function createBox() {
    const div = document.createElement('div');
    div.classList.add('mystyle');
    div.style.backgroundColor = 'white';
    div.addEventListener('click', () => {
      let boxColor = div.style.backgroundColor;
      if (boxColor === 'white') {
        div.style.backgroundColor = 'red';
      } else {
        div.style.backgroundColor = 'white';
      }
    });
    return div;
  }

  React.useEffect(() => {
    for (let i = 0; i < value; i  ) {
      const boxElement = createBox();
      boxRef.current.appendChild(boxElement);
    }
  }, [value]);

  function handleBoxCreate({ target: { value } }) {
    setValue(value);
  }

  return (
    <div>
      <h1>BOX CREATE</h1>
      <input type="number" name="boxInput" onChange={handleBoxCreate} />
      <div ref={boxRef}  />
    </div>
  );
}
/* style.css */
.mystyle {
  width: 30px;
  height: 30px;
  border: 2px solid black;
  display: inline-block;
  padding: 2px;
  margin-right: 5px;
}

Do I need to cleanup the dom. if so how to do it?. or is there any better way to implement the same.

Please help. ty:)

CodePudding user response:

You should avoid doing direct manipulations on the DOM. Instead create a "Box" react component and render it based on the amount of your value state.

import React from "react";
import "./styles.css";

const Box = () => {
  const [color, setColor] = React.useState("white");

  const onClick = () => {
    if (color === "white") {
      setColor("red");
    } else {
      setColor("white");
    }
  };
  return (
    <div
      className="mystyle"
      style={{ backgroundColor: color }}
      onClick={onClick}
    />
  );
};

export default function App() {
  const [value, setValue] = React.useState(0);

  function handleBoxCreate({ target: { value } }) {
    setValue(Number(value));
  }

  return (
    <div>
      <h1>BOX CREATE</h1>
      <input type="number" name="boxInput" onChange={handleBoxCreate} />
      {[...Array(value)].map((e, i) => (
        <Box key={i} />
      ))}
    </div>
  );
}

  • Related