Sorry for my English is not very good. I'm learning React. I'm going to make a todo app. I want the 'input' content to appear as h4 when I press the button. But I can't map. Where do you think is the mistake?
import "./App.css";
import { useRef, useState } from "react";
function App() {
const [state, setState] = useState([]);
const inp = useRef(null);
const Add = () => {
setState([...state, inp.current.value]);
};
return (
<div className="App">
<input name="inp" ref={inp} />
<button onClick={Add}>Add</button>
{state.map((e) => {
<h4>{e}</h4>;
})}
</div>
);
}
export default App;
CodePudding user response:
Change this
return (
<div className="App">
<input name="inp" ref={inp} />
<button onClick={Add}>Add</button>
{state.map((e) => {
<h4>{e}</h4>;
})}
</div>
);
into this
return (
<div className="App">
<input name="inp" ref={inp} />
<button onClick={Add}>Add</button>
{state.map((e) => {
return (
<h4>{e}</h4>;
)
})}
</div>
);
You forgot to return the element in map.
There are two ways of doing it.
// 1
array.map((el) => ( <div>{el}</div> ))
// 2
array.map((el) => { return <div>{el}</div> })
CodePudding user response:
the problem is in inp.current.value
you need to change it to
const Add = (evt) => {
var val = evt.target.value;
setState([...state, val]);
};
let me know if it work