0

I have created two components App and leftBar. I'm getting the Class component props in App component. But the same prop is empty in LeftBar.

Index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch} from 'react-router-dom';


/** Component **/
import App from './App';


ReactDOM.render(
    <BrowserRouter>
    <Switch>
        <Route path="/:folders/:actions" component={App}></Route>
    </Switch>
</BrowserRouter>, document.getElementById('app'));

App.js

import React, {Component} from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';

import LeftBar from './components/left-bar';

class App extends Component {
 constructor(props){
    super(props);
    console.log(this.props); //Returns the object
  }

render(){
   return (
     <LeftBar />
   )
  }
}

LeftBar.js

class LeftBar extends Component{
  constructor(props) {
        super(props);
        this.state = {
            leftBar: ["sarath"]
        }
        console.log(this.props); //this returns empty object {}
    }
}

someone point out what was the issue behind this. I want to use props across the multiple components.

0

2 Answers 2

2

react-router will not pass props down the way you are hoping. You need to first pass props to App by doing

// ...
<Route path="/:folders/:actions" component={props => <App {...this.props} />} />

Then you need to pass them along in your child component(s). I am including this.state with the assumption you want to use this inside of LeftBar but you may remove {...this.state} if that is incorrect:

// ...
render () {
    return (
        <LeftBar 
            {...this.props} 
            {...this.state} />
    )
}
Sign up to request clarification or add additional context in comments.

2 Comments

I called the console.log after the leftBar: ["sarath"] was set. Still I'm getting {}.
yes, because you are setting this.state = { leftBar: ["sarath"] }. this.state is not this.props
1

Because you don't assign any props on <LeftBar />.

You have to pass the required props to this component as well:

render(){
 return (
   <LeftBar {...this.props}/>
 )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.