xxxxxxxxxx
//this example is for adding user to list
import React, { useState } from 'react';
const [users,setUsers] = useState([
{id:1,name:"John Doe"},{id:2,name:"Merry"},
]);
const [name,setName] = useState('');
const [password,setPassword] = useState('');
function onSubmitHandler(e){
e.preventDefault();
console.log(name,password);
const newUser = {id:Date.now(), name, password}
setUsers([users,newUser]);
}
return(
<div classsName="container">
<form onSubmit={onSubmitHandler}>
<input value={name} onChange={ (e) => setName(e.target.value) } />
<input value={password} onChange={ (e) => setPassword(e.target.value) } />
<button type="submit">Create</button>
</form>
<ul>
{users.map(user,index) => {
return (
<li key={user.id}>{user.name}</li>
)
}}
</ul>
</div>
xxxxxxxxxx
useState - Has the main purpose to change an element status
useState basically helps React to know what to elements need to be rerendered.
Ex: We have a post (state: it is displayed)
You want to eliminate the post (setState: it is not displayed)
Code Ex.:
const [blogs, setBlogs] = useState([
{ title: 'React forever', body:'Lorem ipsum...', author: 'Sara', id: 1 },
{ title: 'Vue kinda sucks', body:'Lorem ipsum...', author: 'Tony', id: 2 },
{ title: 'Angular lets not go there', body:'Lorem ipsum...', author: 'John', id: 3 },
]);
// The JS function that filters all the post with diff. id from the id of the post clicked
const handleDelete = (id) => {
const newBlogs = blogs.filter(blog => blog.id !== id);
setBlogs(newBlogs);
}
// React renders the following JSX
return (
<div className="blog-list">
<h2>{ title }</h2>
{blogs.map((blog) => (
<div className="blog-preview" key={blog.id}>
<h3>{ blog.title }</h3>
<p>written by { blog.author }</p>
<p>{ blog.body }</p>
<button onClick={() => handleDelete(blog.id)} className="hideBtn">Hide Post</button>
</div>
))}
</div>
);