简体   繁体   中英

how can i add input value to state in React.js?

im trying to get input value and push it into state when the person click on submit, but i confused.

const App = () => {
    const [category,setCategory] = useState([])
    return ( 
        <div>
            <input type="text" name="" id="" />
            <button type="submit" >Add</button>
        </div>
     );
}
 
export default App;

i tried lot of ways but i coudn't find any solution.

You just need to have another state variable that stores the current input value. Like this:

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>

Try this

 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;

If you don't want to use previousElementSibling then try useRef like this:

 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;

Of course you'll have to import useRef

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM