Passing state back to parent component in React
One thing that makes a great developer stand out from the average ones is the ability to write clean, well-formatted code.
This is the brains behind React's functionality, which allows coders to store information and perform actions within one component, and then have another component access the data and use it. This is the relationship between child and parent components in React.
The parent or original component already has an action to process. A coder that wants to perform another process to replace, update, or add data to the parent component creates a child component to perform this operation.
In some cases, developers may want to pass multiple data to the parent. Creating multiple child components is also an ideal approach.
This will result in a shorter and cleaner parent component with less code.
callback
Function is a React concept that allows you to call a function after processing the action of that function. This is a direct way to call a function in a child component back to the parent component.
We will start by creating a new project from the terminal. We type npx create-react-app illustrationone
.
After creating the project, we go to the folder in the editor, move to src
the folder and create a new file . We will use and Child.js
in our examples .App.js
Child.js
Our <div> App.js
will serve as our parent component, and we’ll initiate callback
the <div> function like this:
Code snippet ( App.js
):
import React from 'react';
import Child from './Child'
class App extends React.Component{
state = {
name: "",
}
handleCallback = (childData) =>{
this.setState({name: childData})
}
render(){
const {name} = this.state;
return(
<div>
<Child parentCallback = {this.handleCallback}/>
{name}
</div>
)
}
}
export default App
We first create name
the state and then declare the callback function that will Child.js
get name
the data corresponding to the variable from the component.
Once we get the data back from the child component, we'll create a function that will return the data assigned to the variable Child.js
in .name
Next, we go to Child.js
, where we declare the operations we want to perform.
Code snippet ( Child.js
):
import React from 'react'
class Child extends React.Component{
onTrigger = (event) => {
this.props.parentCallback(event.target.myname.value);
event.preventDefault();
}
render(){
return(
<div>
<form onSubmit = {this.onTrigger}>
<input type = "text"
name = "myname" placeholder = "Enter Name"/>
<br></br><br></br>
<input type = "submit" value = "Submit"/>
<br></br><br></br>
</form>
</div>
)
}
}
export default Child
Output:
Because we want to pass this data back to the parent component, we need a function to kick off the function inside the child component callback
. This is where we need onTrigger
an event listener.
As soon as we click Submit
the button and display the result, the function onTrigger
is immediately activated callback
, passing name
the value assigned to the variable back to the parent component.
This is a more direct approach than the previous example. We use props
to return the processed result to the parent component.
We navigate to src
the folder and create a new file User.js
. This will be our child component.
App.js
is our parent component, to which we will pass this code:
Code snippet ( App.js
):
import React from 'react'
import './App.css';
import User from './User'
function App() {
function getName(name) {
alert(name)
}
return (
<div className="App">
<h1>Returning State Back to Parent</h1>
<User getData={getName} />
</div>
);
}
export default App;
We created a name
function, which tells the React framework that we want it to get name
the date assigned to the function. Then we want to alert it, which we want to return in the form of a popup.
Then we User.js
add more code to the child component:
Code snippet ( User.js
):
function User(props)
{
const name="Oluwafisayo"
return(
<div>
<h1>My Name is : </h1>
<button onClick={()=>props.getData(name)} >Click Me</button>
</div>
)
}
export default User;
Output:
Here we assign the data to name
the function and then once Click me
the button is pressed, it activates onClick
the event listener which returns the data to the parent as props. Remember, props
is short for properties.
Since we are passing data from two child components to the parent component, we will create one file for the parent component and two files <data> and <component> TodoList.js
for the child components .Todo.js
DeadlineList.js
The parent component will contain the code that will define the functions to derive the data we want to retrieve from the child component:
Code snippet ( TodoList.js
):
import React from "react";
import Todo from "./Todo";
import DeadlineList from "./DeadlineList";
const TodoList = ({ todos, toggleTodo }) =>
console.log(todos) || (
<table>
<tbody>
<tr>
<th className="taskTH">TASK</th>
<th className="deadlineTH">DEADLINE</th>
</tr>
<tr>
<td className="taskTD">
{todos.map((todo) => (
<Todo
key={todo.id}
text={todo.text}
completed={todo.completed}
toggleTodoItem={() => toggleTodo(todo.id)}
/>
))}
</td>
<td className="deadlineTd">
{" "}
{todos.map(
(todo) =>
console.log("TODO", todo) || (
<DeadlineList
key={todo.id}
value={todo.date}
completed={todo.completed}
onClick={() => toggleTodo(todo.id)}
/>
)
)}
</td>
</tr>
</tbody>
</table>
);
export default TodoList;
Next, we process Todo.js
a form. After entering the data, we click Add Todo
the button, which returns the data:
Code snippet ( Todo.js
):
import React, { useState } from 'react';
import wooHooSound from '../utils/wooHoo.js'
const Todo = (props) => {
const { toggleTodoItem, completed, text } = props;
let [ shouldPlaySound, setShouldPlaySound ] = useState(true);
function wooHooEverySecondClick() {
if (shouldPlaySound) {
wooHooSound.play();
setShouldPlaySound(false);
} else {
setShouldPlaySound(true);
}
}
return (
<li className="bananaLi"
onClick={() => {
toggleTodoItem();
wooHooEverySecondClick();
}}
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
>
{text}
</li>
);
};
export default Todo;
is then DeadlineList.js
responsible for presenting the list to the parent in list format:
Code snippet ( DeadlineList.js
):
import React from "react";
const DeadlineList = ({ onClick, completed, value }) => {
return (
<li
className="deadlineLi"
onClick={onClick}
style={{
textDecoration: completed ? "line-through" : "none"
}}
>
{new Intl.DateTimeFormat("en-US").format(value)}
</li>
);
};
export default DeadlineList;
Then we import App.js
everything in :
Code snippet ( App.js
):
import React from 'react';
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList';
import Footer from './Footer';
const App = () => (
<div className="appCSS">
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
);
export default App;
Output:
When developers build projects as a team, writing coherent and short code for each component can easily get help from teammates. On the contrary, a project with messy code can easily turn off peers who want to help.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Article URL:https://www.jiyik.com/en/xwzj/web_9570.html
Related Articles
How to reverse an array in React
Publish Date:2025/03/13 Views:198 Category:React
-
在 React 中反转数组:使用扩展语法 `(...)` 创建数组的浅表副本。在副本上调用 `reverse()` 方法。将结果存储在变量中。
Setting data attributes in React
Publish Date:2025/03/13 Views:84 Category:React
-
要在 React 中为元素设置 data 属性,请直接在元素上设置属性,例如 或使用 setAttribute() 方法,例如 el.setAttribute('data-foo', 'bar')。 我们可以访问事件对象上的元素或
Toggle a class on click in React
Publish Date:2025/03/13 Views:153 Category:React
-
要在 React 中单击时切换类:在元素上设置 onClick 属性。将活动状态存储在状态变量中。使用三元运算符有条件地添加类。
Sorting an array of objects in React
Publish Date:2025/03/13 Views:77 Category:React
-
在 React 中对对象数组进行排序: 创建数组的浅拷贝。 调用数组的 `sort()` 方法,传递给它一个函数。 该函数用于定义排序顺序。
Generate a random number in React
Publish Date:2025/03/13 Views:189 Category:React
-
使用 Math.random() 函数在 React 中生成一个随机数,例如 Math.floor(Math.random() * (max - min + 1)) + min。 Math.random 函数返回 0 到小于 1 范围内的数字,但也可用于生成特定范围内的数字。
Open links in new tabs with React
Publish Date:2025/03/13 Views:76 Category:React
-
要在 React 的新选项卡中打开链接,请使用 a 元素并将其 `target` 属性设置为 _blank,例如 。 _blank 值表示资源已加载到新选
How to set target=_blank in React
Publish Date:2025/03/13 Views:199 Category:React
-
要在 React 中将元素的目标属性设置为 _blank,请使用锚元素并设置 rel 属性,例如 。 _blank 值表示资源已加载到新选项卡中。
Showing hover elements in React
Publish Date:2025/03/13 Views:177 Category:React
-
要在 React 中显示悬停元素:在元素上设置 `onMouseOver` 和 `onMouseOut` 属性。 跟踪用户是否将鼠标悬停在状态变量中的元素上。 根据状态变量有条件地渲染其他元素。
Passing components as props in React
Publish Date:2025/03/13 Views:164 Category:React
-
我们可以使用内置的 children 属性在 React 中将组件作为属性 props 传递。 我们在组件的开始标签和结束标签之间传递的所有元素都会分配给 children 属性。