Skip to content
Advertisement

Is there a way to create a dynamic state and setState in React

I have the following deceleration: const [open1, setOpen1] = useState(false);

and would like to generate this as many as I fetch records from the database (for every record fetched ) I need new [open, setopen]

here is my for loop used in my code.

        <Container fluid={true} className="text-center">
          <div
            className="questionrectangle "
            onClick={() => setOpen1(!open1)}
            name="step-one"
            aria-controls="example-collapse-text"
            aria-expanded={open1}>
            <p className="questiontext "> {post.QString}</p>
          </div>
          <Collapse in={open1} name="step-two">
            <p className="questionanswer">{post.Answer}</p>
          </Collapse>
        </Container> ```

If you have any idea I would be appreciated 

Advertisement

Answer

Create separate component to hold ‘open’ state. Something like this..

function QuestionAnswer({post}) {
  const [open1, setOpen1] = useState(true);

  return (
    <>
      <div
        className="questionrectangle "
        onClick={() => setOpen1(!open1)}
        name="step-one"
        aria-controls="example-collapse-text"
        aria-expanded={open1}
      >
        <p className="questiontext "> {post.QString}</p>
      </div>
      {open1 && (
        <div name="step-two">
          <p className="questionanswer">{post.Answer}</p>
        </div>
      )}
    </>
  );
}

Now, from your main application fetch the data and create one component for each Post – like this

  // Replace this with fetch request
  const data = [
    { QString: "Question 1", Answer: "answer 1" },
    { QString: "Question 2", Answer: "answer 2" },
    { QString: "Question 3", Answer: "answer 3" }
  ];

  return (
    <Container fluid={true} className="text-center">
      {data.map((post) => (
        <QuestionAnswer post={post} />
      ))}
    </Container>
  );
}

Now, each component will hold its own copy of ‘Open’ state and will be able to handle individual open and close state.

You can see complete sample

https://codesandbox.io/s/beautiful-surf-ejron

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement