0

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.

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

I would use an object rather than array: [name]: value.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.