How to pass state from parent component to child component in route (react to route)

I am new to React.js and created a small react app using react-router-dom

. In which I have two components:

  1. Panel (dashboard.js)
  2. Information (information.js)

and one main app for apps, App.js, which I am using react-router-dom

.

<Route exact path="/dashboard" render={props => <Dashboard someProp="2" {...props} />} />
<Route exact path="/information" render={props => <Information someProp="2" {...props} />} />

      

I can send props from the App component to the dashboard and information, but I want to send the state. Can anyone help me, How can I send state from parent component to child component?

+2


source to share


2 answers


In the parent component, you can send props like this



<child prop1 = {this.state.stateName} />

      

+2


source


Using the above answer, I am posting the complete code for further users to understand.

App.js file

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {open: false};
    this.state = {message: "StackOverflow"};
  }

return (
        <Router>
          <div>
          <AppBar title="App" onLeftIconButtonTouchTap={this.handleToggle} />

            <Drawer containerStyle={{height: 'calc(100% - 64px)', top: 64}} docked={true} width={200} open={this.state.open} zDepth={2}>
              <Link to="/dashboard" style={{ textDecoration: 'none' }}><MenuItem>Dashboard</MenuItem></Link>
              <Link to="/information" style={{ textDecoration: 'none' }}><MenuItem>Information</MenuItem></Link>
            </Drawer>

            <Route exact path="/dashboard" render={props => <Dashboard someProp={this.state.message} {...props} />} />
            <Route exact path="/information" render={props => <Information someProp={this.state.message} {...props} />} />
          </div>
        </Router>
    );
}

      



Dashboard.js

import React from 'react';


class Dashboard extends React.Component {

  constructor(props) {
    super(props);
  }

  render() {
    console.log(this.props);
    const {styleFromProps} = this.props;
    const contentStyle = {  ...styleFromProps, transition: 'margin-left 450ms cubic-bezier(0.23, 1, 0.32, 1)' };

    return (
            <div style={contentStyle}><h1> Hello {this.props.someProp}</h1></div>
    );
  }
}

export default Dashboard;

      

+1


source







All Articles