JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Passing state back to parent component in React

Author:JIYIK Last Updated:2025/03/03 Views:

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.

callbackFunction 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 srcthe folder and create a new file . We will use and Child.jsin our examples .App.jsChild.js

Our <div> App.jswill serve as our parent component, and we’ll initiate callbackthe <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 namethe state and then declare the callback function that will Child.jsget namethe 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.jsin .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:

Use callback function to pass state to parent

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 onTriggeran event listener.

As soon as we click Submitthe button and display the result, the function onTriggeris immediately activated callback, passing namethe value assigned to the variable back to the parent component.

This is a more direct approach than the previous example. We use propsto return the processed result to the parent component.

We navigate to srcthe folder and create a new file User.js. This will be our child component.

App.jsis 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 namefunction, which tells the React framework that we want it to get namethe 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.jsadd 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:

Passing state to parent using props

Here we assign the data to namethe function and then once Click methe button is pressed, it activates onClickthe event listener which returns the data to the parent as props. Remember, propsis 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.jsfor the child components .Todo.jsDeadlineList.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.jsa form. After entering the data, we click Add Todothe 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.jsresponsible 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.jseverything 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:

React passes state from multiple child components to parent component

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:

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.

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.

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

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial