Reputation: 530
I have an App, a Navbar and a Content class, I am trying to pass a prop from navbar to content that will be rendered when I redirect to the content page.
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import Navbar from './components/Home/Navbar';
import Content from './components/Home/Content';
export default class App extends Component {
render() {
return (
<Router>
<div>
<Navbar />
<Route path="/content" component={Content} render={(props) => <Navbar {...props} test={this.state.test} />} />
</div>
</Router>
);
}
}
import React from 'react';
class Navbar extends React.Component {
constructor(props) {
super(props);
this.state = {
test: 'test',
}
}
render() {
return (
<div>
This is my navbar
</div>
);
}
}
export default Navbar;
import React from 'react';
class Content extends React.Component {
constructor(props) {
super(props);
this.state = {
x: 'x',
test: this.props.test
}
}
render() {
return (
<div>
<p>{this.state.x}</p>
<p>{this.state.test}</p>
</div>
);
}
}
export default Content;
The problem that I am having is that is when I redirect to the content page, the state from the navbar class is not being passed through to it. How do I fix this?
Upvotes: 0
Views: 60
Reputation: 12796
The problem mostly lays in the fact that you are using both component
and render
props in your Route
, you should use only one. If you do not want to change or pass along anything from where your Route
is defined, you should use component
property.
If you do wish to pass along some information at that point, use the render
prop as you have done (however, I believe you really wanted to render the Content
component and not the NavBar
as in your OP)
<Route path="/content" render={(props) => <Content {...props} test={this.state.test} />} />
Then you really don't need any of your local state you were displaying, and content could be a functional component instead, like
const Content = ({ x, test }) => (
<>
<p>{ x }</p>
<p>{ test }</p>
</>);
where x
and test
would be destructured from your props, giving you easy access to it (you could also use (props)
and then props.test
and props.x
depending on how you like to write it)
Upvotes: 1
Reputation: 3497
u can pass state like this with redirect :
<Redirect to={{
pathname: '/content',
state: { test: '123' }
}}
/>
and for accessing it :
this.props.location.state.test
Upvotes: 0