0

I have this layout

enter image description here

DESIRED BEHAVIOUR

In the start there is only one input. First one. And it is empty. When i type something in it and press 'ADD +' new input under that one is created , it is disabled and it has value of first one that I was typing in. First one is then cleared and it is empty again. I really have no idea how to make this.



This is the code that I currently have.

const FilterListInput = ({ data }) => {
  const [comp, setComp] = useState('');
  const [rows, setRows] = useState([[]]);

  console.log(rows);

  const handleChange = (e, index) => {
    rows[index] = e.target.value;
    setRows(rows);
  };

  return (
    <>
      <div className="filter__form__elements__element">
        <label htmlFor={data.name}>{data.labelName}</label>
        <For
          of={rows}
          render={(item, index) => (
            <>
              <Input
                name={item.name}
                placeholder={data.placeholder}
                onChange={(e) => handleChange(e, index)}
              />
            </>
          )}
        />
      </div>
      <Button title="ADD +" type="secondary" onClick={() => setRows([...rows, comp])} />
    </>
  );
};

I am stuck here and I have no idea where to go next. Currently when I create new input I can type in it and data from the first one is left in it which I don't want. Also I want everything to be saved in rows hook.

I am not asking for full code. Just some guidlines.

Thank you in advance

1 Answer 1

1

as far as I understand your desired behaviour -> 1. you want to start with one empty input, and when pressing the + button, you want to add a new empty input to the start of the list. 2. all inputs but the first one should be disabled.

I don't think you need the comp state, only the rows state. rows state should be 1D array (not 2D)

  • state should be init with one empty string const [rows,setRows] = useState([''])
  • when rendering the inputs if index > 0 input should be disabled.
  • when pressing the + button you need to add a new row to the start setRows['',...rows]
  • on your handleChange function just make sure you are replacing the array so the component will rerender. something like

    const handleChange = (e, index) => { const newRows = [...rows]; newRows[index] = e.target.value; setRows(newRows); };

hope it helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.