Articles → REACT.JS → Store A List In The State Using The Usestate Hooks In React.Js

Store A List In The State Using The Usestate Hooks In React.Js






Example




import ReactDOM from 'react-dom'
import { useState } from 'react';


const Home = () => {

    const [name, setName] = useState("");

    const [nameList, setNameInList] = useState([]);

    const handleClick = (event) => {
        event.preventDefault();
        setNameInList([name, ...nameList]);
    }

    const nameChangeHandler = (event) => {
        
        setName(event.target.value);
    }

 

    return (
        <form>
            <div>
                Name:
                <p><input type="text" name="nameField" onChange={nameChangeHandler} /></p>
                <button onClick={handleClick}>Click me</button>

                <ul>
                    {nameList.map(myname => <li key={myname}>{myname}</li>)}
                </ul>

            </div>
        </form>
    );
}

ReactDOM.render(<Home />, document.getElementById('root'));



Output


Picture showing the output of how to store a list in the state using the useState hooks in react.js

Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Saturday, September 11, 2021

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250