I am learning react and got stuck with this problem.
I have created a state for users with two properties name & tweet on my App.js component and Tweet.js component fetches the data from the state and outputs the tweet on the DOM.
I want to create a new user in my state when the form is submitted. How can i do so?
App.js
import React, {useState} from 'react';
import Tweet from './Tweet';
function App () {
const [users, setUsers] = useState([
{name:'Coulson', tweet:'Avengers Assemble'},
{name:'Rick', tweet:'Living in world of dead.'},
{name:'Barry', tweet:'I am the Flash.'},
{name:'Judith', tweet:'Hi Carl.'},
{name:'Michonne', tweet:'I have a katana.'},
{name:'Bob', tweet:'Lets build something.'},
])
return(
<div className="App">
<div className="form">
<form>
<label htmlFor="name">Name</label> <input type="text" />
<label htmlFor="tweet">Tweet</label> <input type="text" />
<button>Submit</button>
</form>
</div>
{users.map(user => (
<Tweet name={user.name} tweet={user.tweet} />
))}
</div>
)
}
export default App;
Tweet.js
import React from 'react'
import "./App.css"
function Tweet ({name, tweet, likes}) {
return(
<div className="tweet">
<h3>{name}</h3>
<p>{tweet}</p>
<h3>Likes: {likes}</h3>
</div>
)
}
export default Tweet;
First off, you probably want to maintain controlled inputs for your form to give you more control over what goes on in them and to access the form data more easily.
const [name, setName] = React.useState("");
const [tweet, setTweet] = React.useState("");
const handleChangeName = (e) => {
setName(e.target.value);
}
const handleChangeTweet = (e) => {
setTweet(e.target.value);
}
...
<label htmlFor="name">Name</label>
<input type="text" value={name} onChange={handleChangeName}/>
<label htmlFor="tweet">Tweet</label>
<input type="text" value={tweet} onChange={handleChangeTweet}/>
Then you'd need to write a submit handler function which is called when the form is submitted, inside which you can access the form data you've been tracking and update the users array:
const handleSubmit = (e) => {
e.preventDefault();
const newUser = { name, tweet };
setUsers([...users, newUser])
}
I made an example here.