Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing data between two sibling React.js components

I have two instances of a component (a search field) on a page, with a second component (a button that makes server calls) between them, as such:

ReactDOM.render(
    <table>
    <tbody>
        <tr>
            <td><CardSearch items={ cards } placeholder="Card 1 here" /></td>
            <td><RunOnServer url="py/comparecards" /></td>
            <td><CardSearch items={ cards } placeholder="Card 2 here"/></td>
        </tr>
    </tbody>
    </table>,
    document.getElementById('root')
);

All I want to do is pass one parameter each, unmodified, from the CardSearch fields to the RunOnServer button, but I'll be damned if it's easy. According to this I can use this.state.var as a prop, but doing that gave me 'undefined.state.var' when the code compiled instead. React's official docs are not great; they simply tell me to go Flux myself, which seems daft... I shouldn't need a whole new architecture to pass a simple variable from one component to another.

I also tried making local vars in the file that's doing the rendering, but they get passed to the components as props and you can't modify props in a component.

like image 833
IronWaffleMan Avatar asked Jan 12 '16 01:01

IronWaffleMan


People also ask

How do you pass data between two sibling components in React?

To move data from a component to a sibling component, the simplest way is to pass a function from the parent component as a prop (i.e. "prop function") to its child that wants to update the data.

How do you pass data from one component to another in react JS?

For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.

How do you send data from child to child in React?

To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .

How to pass data between components in ReactJS?

We have multiple ways of passing data among components. We can pass data from parent to child, from child to parent, and between siblings. So now let’s see how can we do so. Step 1: Create a React application using the following command. Step 2: After creating your project folder i.e. myapp, move to it using the following command.

How to share data between siblings in ReactJS?

Take the following steps: In the Parent.js, set a callback function to take in the parameter that you have accessed from the child. Send the callback function to the child1.js as a prop. Pass your data using this.props.callback (dataToParent) in the child1.js. Choosing a method to share data among sibling can be a bit tricky for beginners.

How to move data from a component to a sibling component?

To move data from a component to a sibling component, the simplest way is to pass a function from the parent component as a prop (i.e. "prop function") to its child that wants to update the data.

How to get the data from parent to child in react?

import React, { Component } from 'react' export default class Child extends Component { render () { return ( <div> {this.props.parentToChild} </div> ) } } Either way, you will get the same results: When we click the Click Parent button, we will see the data as output on the screen.


Video Answer


2 Answers

I created a jsfiddle with an example of how to share a variable between two components using a parent component.

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {shared_var: "init"};
    }

    updateShared(shared_value) {
        this.setState({shared_var: shared_value});
    }

    render() {
        return (
            <div>
                <CardSearch shared_var={this.state.shared_var} updateShared={this.updateShared} />
                <RunOnServer shared_var={this.state.shared_var} updateShared={this.updateShared} />
                <div> The shared value is {this.state.shared_var} </div>
            </div>
        );
    }
}

class CardSearch extends React.Component {
    updateShared() {
        this.props.updateShared('card');
    }

    render() {
        return (
            <button onClick={this.updateShared} style={this.props.shared_var == 'card' ? {backgroundColor: "green"} : null} >
            card
            </button>
        );
    }
}

class RunOnServer extends React.Component {
    updateShared() {
        this.props.updateShared('run');
    }

    render() {
        return (
            <button onClick={this.updateShared} style={this.props.shared_var == 'run' ? {backgroundColor: "green"} : null}>
            run
            </button>
        );
    }
}


ReactDOM.render(
  <Parent/>,
  document.getElementById('container')
);
like image 59
Mark Avatar answered Oct 07 '22 18:10

Mark


As of 2020, Feb; Context API is the way to handle this:

// First you need to create the TodoContext


// Todo.jsx
//...
export default () => {
  return(
    <>
      <TodoContextProvider>
        <TodoList />
        <TodoCalendar />
      </TodoContextProvider>
    </>
  )
}

// Now in your TodoList.jsx and TodoCalendar.jsx; you can access the TodoContext with:
//...
const todoContext = React.useContext(TodoContext);
console.log(todoContext)
//...
//...

Check this video tutorial by The Net Ninja for Hooks & Context API

Good Luck...

like image 43
Aakash Avatar answered Oct 07 '22 17:10

Aakash