1

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

0

1 Answer 1

1

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.

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

2 Comments

thank you dear Duenna, but in your code when I want to delete some text it again renders all list
I'm not going to do it all for you, but the errors are fixed and this should be a good jumping off point for you to figure out the last bit!

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.