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

Time:02-26

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.

CodePudding user response:

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>

CodePudding user response:

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

  • Related