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.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:188 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:187 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:102 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:172 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:153 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:60 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:191 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:78 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:90 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap