Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!