Estoy tratando de obtener el valor de entrada y ponerlo en estado cuando la persona haga clic en enviar, pero me confundí.
const App = () => { const [category,setCategory] = useState([]) return ( <div> <input type="text" name="" id="" /> <button type="submit" >Add</button> </div> ); } export default App;Intenté muchas maneras pero no pude encontrar ninguna solución.
Solo necesita tener otra variable de estado que almacene el valor de entrada actual. Como esto:
const [categories, setCategories] = useState([]); const [category, setCategory] = useState(''); const addCategory = () => { setCategories([...categories, category]); // after pushing the value, you may want to reset the input field setCategory(''); }; ... <input value={category} onChange={(e) => setCategory(e.target.value)} /> <button onClick={addCategory}>Add</button>Prueba esto
const App = () => { const [category,setCategory] = useState([]) const addCategory = e => { const newCategory = category newCategory.push(e.target.previousElementSibling.value) setCategory(newCategory) } return ( <div> <input type="text" name="" id="" /> <button type="submit" onClick={addCategory}>Add</button> </div> ); } export default App; Si no desea usar el elemento previousElementSibling , intente usarRef de esta manera:
const App = () => { const catRef = useRef(null) const [category,setCategory] = useState([]) const addCategory = e => { const newCategory = category newCategory.push(catRef.current.value) setCategory(newCategory) } return ( <div> <input type="text" name="" ref={catRef} id="" /> <button type="submit" onClick={addCategory}>Add</button> </div> ); } export default App;Por supuesto, tendrás que importar useRef