Reputation: 19680
I want to pass the prop productId from the home component to the main component.
How can i pass some initial state when i navigate to a new component
home component
let productId = "123" // get from query string
return (
<Button className="startButton"
variant="contained"
color="primary"
component={Link} to="/main"
fullWidth>
Start
</Button>
)
main component
export class Main extends Component {
constructor(props) {
super(props);
this.state = {
productId: "",
}
}
}
Then in my main component i can set the state of that productId.
router
const Router = () => {
return (
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path="/main" component={Main} />
</Switch>
)
}
export default Router;
I am using the following library https://reacttraining.com/react-router/web/guides/quick-start
Update: https://reacttraining.com/react-router/web/guides/basic-components/route-rendering-props
You can see here the example passes in some extra property someVariable
i want to be able to do that.
Upvotes: 1
Views: 2711
Reputation: 436
Try something like wrapperLink component which is given below. In the given example I have given constant state value instead give the value dynamically
import React, { Fragment } from "react";
import ReactDOM from "react-dom";
import Tabs from "@material-ui/core/Tabs";
import Tab from "@material-ui/core/Tab";
import { Switch, Route, Link, BrowserRouter } from "react-router-dom";
import "./styles.css";
const wrapperLink = (state, path) =>
React.forwardRef((props, ref) => (
<Link
innerRef={ref}
to={{
pathname: path,
state: {
...state
}
}}
{...props}
/>
));
const state = {
title: "sample"
};
function App() {
return (
<BrowserRouter>
<div className="App">
<Route
path="/"
render={({ location }) => (
<Fragment>
<Tabs value={location.pathname}>
<Tab label="Item One" component={Link} to="/" />
<Tab label="Item Two" component={wrapperLink(state, "/tab2")} />
<Tab
label="Item Three"
href="#basic-tabs"
component={Link}
to="/tab3"
/>
</Tabs>
<Switch>
<Route
path="/tab2"
render={props => <div>{props.location.state.title}</div>}
/>
<Route path="/tab3" render={() => <div>Tab 3</div>} />
<Route path="/" render={() => <div>Tab 1</div>} />
</Switch>
</Fragment>
)}
/>
</div>
</BrowserRouter>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here is working example in codesandbox click here
Upvotes: 2
Reputation: 188
If I clearly understand you don't need to pass, since they are already available in properties match Object.
export class Main extends Component {
constructor(props) {
super(props);
const {productId} = props.match.params;
this.state = {productId}
}
}
Upvotes: -1