1

I am a react beginner, and I am trying to grab the value onChange of input and push it to a list then map through it and print it. Something goes wrong and i get no warnings. Can someone explain to me please what I am doing wrong.

 import { useState } from "react";
 import "./App.scss";

 function App() {
     const [list, setLists] = useState([]);
     const [todos, setTodos] = useState([]);

     const trackList = (e) => {
     setLists(e.target.value);
     };

      const addTodos = () => {
      const newArray = [...list];
      setTodos(newArray);
     };

     return (
         <div className="App">
           <input onChange={trackList} type="text" />
           <button onClick={addTodos}>Add</button>
           <ul>
             {todos.map((todo) => {
             <li>{todo}</li>;
            })}
          </ul>
        </div>
         );
        }

     export default App;
jj-ammar
  • 35
  • 5
  • This looks to be a duplicate of: https://stackoverflow.com/questions/62714981/react-adding-an-item-to-a-list-from-an-input-by-clicking-submit-button – pallasite99 Mar 25 '23 at 08:02

1 Answers1

0
  1. Use a single state variable to store the input value.
const [val, setVal] = useState('');

<input onChange={e => setVal(e.target.value)} value={val} type="text" />
  1. Add a new item to the end of the array with spread syntax.
const addTodos = () => {
    setTodos([...todos, val]);
};
  1. Don't put curly braces around the body of the map callback so that the value of the single expression inside is returned.
<ul>
  {todos.map((todo) => (
    <li>{todo}</li>
  ))}
</ul>

Putting it all together:

function App() {
  const [val, setVal] = React.useState("");
  const [todos, setTodos] = React.useState([]);

  const addTodos = () => {
    setTodos([...todos, val]);
  };

  return (
    <div className="App">
      <input onChange={(e) => setVal(e.target.value)} value={val} type="text" />
      <button onClick={addTodos}>Add</button>
      <ul>
        {todos.map((todo, i) => (
          <li key={i}>{todo}</li>
        ))}
      </ul>
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div id="root"></div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80