By clicking on a checkbox the next component appears

Asked

Viewed 45 times

0

I would like to know the best way to start rendering this first object and when you click on the checkbox it will render the next one, hiding the previous one and so on.

const [expensesData, setExpensesData] = useState([
    {
      position: 0,
      label: 'Descrição',
      show: true,
      value: '',
    },
    {
      position: 1,
      label: 'Valor',
      show: false,
      value: '',
    },
    {
      position: 2,
      label: 'Categoria',
      show: false,
      value: '',
    },
    {
      position: 3,
      label: 'Data',
      show: false,
      value: '',
    },
    {
      position: 4,
      label: 'Pago com',
      show: false,
      value: '',
    },
    {
      position: 5,
      label: 'Repete',
      show: false,
      value: '',
    },
    {
      position: 6,
      label: 'Pago',
      show: false,
      value: '',
    },
  ]);

  const handleShowNextOption = useCallback(
    index => {
      console.log(index);
    },
    [expensesData],
  );

  return (
    <>
      <Container>
        <Header />
        <Form ref={formRef} onSubmit={handleSubmit}>
          <OptionsContainer>
            {expensesData.map((item, index) => (
              <>
                {item.position === index && item.show && (
                  <OptionItem>
                    <span>{item?.label}</span>
                    <Input name="description" type="text" value={item?.value} />
                    <input
                      type="checkbox"
                      onClick={() => handleShowNextOption(index)}
                    />
                  </OptionItem>
                )}
              </>
            ))}
          </OptionsContainer>
        </Form>
      </Container>
    </>
  );
};





1 answer

0

Fala Yuri!

You can maintain a state that represents the open object/component by referencing a unique value of each object (in your case it would be the position). When you check a checkbox, you set the state to the next item position (be careful not to set a position that does not exist). And at render you can check if the value of this state matches the position of the item in the array

Another alternative, which is very close to what you did is to assign the same function to all checkbox, and when checked the checkbox, you pass to the function the position of the object that is in interaction with the user, and in the function you arrow the show of that object as false and the show of the next object (position + 1) as true.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.