Well, things can become really complicated in React and there's no reason for that. At least, as a beginner, you should be able to understand States without falling asleep 💤 💤 by counting a dozen technical slangs.
So a
State
is an object, just likeprops
.
Note: You might want to check state vs. props and it may drive you crazy 😵💫, so just think that the use of state
results in significant performance improvements in larger apps. We need State. Now relax.🛀
To use a state you need to import the useState, like this:
import React, { useState } from "react";
State is wonderful to work with; it returns the state value and the function to update that value.
const [item, updateItem] = useState(""); // item=""
You can use updateItem("hello!")
to update item
. Let's see a real world example with a form component:
import React, { useState } from "react";
function AddItemForm() {
const [item, updateItem] = useState("");
const valueChangeHandler = (e) => {
updateItem(e.target.value);
};
return (
<div>
<form>
<div className="field">
<label className="label">Title</label>
<div className="control">
<input
onChange={valueChangeHandler}
value={item}
className="input"
type="text"
placeholder="Title"
></input>
// and so on
So, we have a form. We introduce a state value (item="") and every time the user inputs something on the input field, we update the item
value using the updateItem
function. Notice that we make sure that value={item}
, so with every onChange
event, the value of the input is updated. You could use the item
in any other place ofcourse.
I think that was fairly simple, right? :)
Now, States are used to chain updates, so it is important to understand that you can submit the form and pass data with the onSubmit
event to the App (or any other component).
To do this, you need to add props
to the component like this:
function AddItemForm(props) {
const [item, updateItem] = useState("");
Then you need to create a function to use for the onSubmit
event:
const submitHandler = (e) => {
e.preventDefault(); // so that page will not reload
props.onSubmitData(item); //item *goes up* to the App :)
};
You will call the submitHandler
like this on your form component:
<form onSubmit={submitHandler}>
Now you need to perform some changes on the App as well. The above example will only work if a onSubmitData
prop has been defined for the form component in the App, like this:
return (
<AddItemForm onSubmitData={getFormData} /> //AddItemForm is the form component
//and so on
Last, you need to pass the form data from the form component to the App using a function:
const getFormData = (someData) => {
console.log(someData); // someData will return the value of item
};
We passed a form input value (item) from one component to another. Lovely! 💕
Top comments (2)
Hi and welcome to Dev 😀
When you do code snippets if you include the language you're using you will get syntax highlighting, like this.
Example of actual code.
THANK YOU! 🙏🙏🙏