Home > Software design >  adding new values in state using ReactJS
adding new values in state using ReactJS

Time:12-08

I am very new in ReactJS and I have one question and hope you can help me too solve that one.

Here is my code

My question is: could you help me fix my code in such a way, At the end of each list there is always one empty input field as the last entry. So As soon as someone writes something into the last input field, there is automatically pushed another empty input field to the list and When an input field, which is not the last one, is being emptied during the editing, the entry gets removed.

I tried to first of all create state of array

     const [list, setList] = useState([]);
     return (
        <div className="App">
          {list.map((el, i) => {
            return (
              <List
                title={el}
                id={i   1}
                handleChange={(e) => setList(...e.target.value, list)}
              />
            );
          })}
        </div>
      );

And also I created List component for rendering my inputs

    const List = ({ title, id, handleChange }) => {
     return (
       <div>
          {id}
          <input onChange={handleChange} value={title} />
       </div>
      );
    };

But I have a bunch of errors, please help me to solve this problem, I will be very thankful for you.

here is final result

CodePudding user response:

I made changes in your code. Try this:

https://codesandbox.io/s/blazing-dream-3u6xh

This link supports delete item:

https://codesandbox.io/s/busy-meadow-yw0tg

CodePudding user response:

I've made edits to your code, try this:

https://codesandbox.io/s/gifted-lumiere-32wg5?file=/src/App.js

In short, you'll want to render a text input after your list map to ensure there is always an extra blank one at the end.

This also means you'll need to keep its state so a new value state needs to exist, I made it so that when you press the enter key it will add it into the list for you.

You are also able to properly update list items now as well.

  • Related