call react component in loop based on onclick button function which sets the state to true once button is clicked

Viewed 600

I am new in react, i am trying to get component based on if button is clicked and once the component is returned to Ui, i want to change button state back to original(false),so if i click on that button again i should get again new component below to the previous one,and this should just go on.., in below code i am able to get this just one time.

const Command = () => {
  const [buttonState, setButtonState] = useState(false);

  const AndOrHandler = () => {
    if (buttonState) {
      return (
        <div>
          <Grid container>
            <SomeComponent />
          </Grid>
        </div>
      );
    }
    return null;
  };


  return (
    <Fragment>
      <FormControl>
        <SomeComponent />
        <AndOrHandler />
        <Button onClick={() => setButtonState(true)} variant="contained" color="primary">Add Condition</Button>
      </FormControl>
    </Fragment>
  );
};

export default Command;
1 Answers

You want continue adding component, i suggest have state components:

const Command = () => {
    const component =  <div>
        <Grid container>
            <SomeComponent />
        </Grid>
    </div>;
    
    const [components, setComponents] = useState([]);

    return (
        <Fragment>
            <FormControl>
                <SomeComponent />
                {components.map(component => component)}
                <Button onClick={() => setComponents([...components, component])} variant="contained" color="primary">Add Condition</Button>
            </FormControl>
        </Fragment>
    );
};

export default Command;
Related