With the react-router v5, we can create routes by wrapping with a component, so that we can easily pass props to the desired component like this. You could also use the RouteHandler mixin to avoid the wrapper component and more easily pass down the parent's state as props: Note that I use render instead of component. The reason is to avoid undesired remounting. I also pass the props to that method, and I use the same props on the Comments component with the object spread operator (ES7 proposal). Using a custom route component, this is possible in React Router v3.
...
<Link to="/props-through-render">Props through render</Link>
...
<Route exact path="/props-through-render" render={(props) => <PropsPage {...props} title={`Props through render`} />} />
If you'd rather not write wrappers, I guess you could do this:
class Index extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>
Index - {this.props.route.foo}
</h1>
);
}
}
var routes = (
<Route path="/" foo="bar" component={Index}/>
);
Since new release, it's possible to pass props directly via the Route
component, without using a Wrapper. For example, by using render
prop.
Component:
class Greeting extends React.Component {
render() {
const {text, match: {params}} = this.props;
const {name} = params;
return (
<React.Fragment>
<h1>Greeting page</h1>
<p>
{text} {name}
</p>
</React.Fragment>
);
}
}
My preferred way is wrap the Comments
component and pass the wrapper as a route handler.
This is your example with changes applied:
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var CommentsWrapper = React.createClass({
render: function () {
return (
<Comments myprop="myvalue"/>
);
}
});
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler/>
</div>
);
}
});
var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={CommentsWrapper}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
However, with React Router v6, since you're in charge of creating the element, you just pass a prop to the component as you normally would. In previous versions of React Router (v4), this was non-trivial since React Router was in charge of creating the React element. To get around this, you'd have to use Routes render prop. Bytes is the developer newsletter I most look forward to each week. Great balance of content and context! Thanks @uidotdev. Now, what if we also wanted to pass the Dashboard component a prop?
<Route path="/dashboard" element={<Dashboard />} />
// React Router v4<Route path="/dashboard" render={(props) => <Dashboard {...props} authed={true} />}/>
<Route path="/dashboard" element={<Dashboard authed={true} />} />
To recap, if you need to pass data from Link through to the new component that's being rendered, pass Links a state prop with the data you want to pass through. There are a few different approaches, but the one we'll focus on in this post is centered around being able to pass data from one route to another. To do this with React Router, we can pass data from the Link component through to the new Route that is being rendered. Anytime you pass data along via the state property, that data will be available on the location's state property, which you can get access to by using the custom useLocation Hook that comes with React Router.
<Link to={`/onboarding/profile`}>Next Step</Link>
<Link to="/onboarding/profile" state={{ from: "occupation" }}> Next Step</Link>
import {
useLocation
} from 'react-router-dom'
function Profile() {
const location = useLocation() const {
from
} = location.state
return (...)
}
Internally, react router use React.createElement to render the component passed to the component props. If we pass a function to it, it will create a new component on every render instead of just updating the existing component. We have seen several examples and use cases in react router. One among them is passing props to the route component directly. React router provides an easy solution for this case. Instead of passing function through component props, we can pass it through render props. While passing our own props, we also need to pass the default props send to the render props by react router. Lets see it in our example,
// App.js
...
const PropsPage = () => { return ( <h3>Props Page</h3> );};
const App = () => {
return (
<section className="App">
<Router>
...
<Link to="/404-not-found">404</Link>
<Link to="/props">Passing Props</Link> <Switch>
...
<Route exact path="/props" component={PropsPage} /> <Route component={NoMatchPage} />
</Switch>
</Router>
<a href="/about">about with browser reload</a>
</section>
);
};
export default App;
...
const PropsPage = ({ title }) => {
return (
<h3>{title}</h3>
);
};
...
<Route exact path="/props-through-component" component={() => <PropsPage title={`Props through component`} />} />
...
<Link to="/props-through-render">Props through render</Link>
...
<Route exact path="/props-through-render" render={(props) => <PropsPage {...props} title={`Props through render`} />} />
With this approach, we can use one link to control the state of another link or share part of elements of one page to another without rendering the entire content of the previous page. The react-router performs the primary function of linking one webpage to the other. When building multi-page apps, we apply the react-router to link the pages together. This approach can prove efficient when we want to add a standout feature or props that we don’t want to lose inside a haystack of codes. So we could create a separate component for it and link it to the page we want while passing in the prop or state.
Then we start with coding up the App.js
file like this:
Code Snippet- App.js
:
import React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import Page4 from './pages/Page4';
import Page5 from './pages/Page5';
function App(props) {
return (
<BrowserRouter>
<Routes>
<Route exact path="/" element={<Page4/>} />
<Route exact path="/page4" element={<Page4 />} />
<Route path="/page5/:type" element={<Page5/>} />
</Routes>
</BrowserRouter>
);
}
export default App;
Then in the Page4.js
file, we put in these codes.
Code Snippet- Page4.js
:
import React from 'react';
import { Link } from 'react-router-dom';
function Page4(props) {
return (
<div>
<h1>Title of Page 4</h1>
<hr />
<Link to={{
pathname: "/page5/parameter-data",
state: { stateParam: true }
}}>Move to Next Page</Link>
</div>
);
}
export default Page4;
Then in Page5
, we create codes that link it back to Page4
, like this.
Code Snippet- Page5.js
:
import React from 'react';
import { Link, useParams, useLocation } from 'react-router-dom';
function Page5(props) {
const { type } = useParams();
return (
<div>
<h1>Title of Page 5</h1>
<hr />
<Link to={"/page4"}>Move to Prev Page</Link>
</div>
);
}
export default Page5;
-1. React JS: Programmatically use React-Router to send props. We'll attempt to use programming in this lesson to solve the React Js Usehistory Push And Pass Props puzzle. This is demonstrated in the code below. By way of numerous illustrations, we have demonstrated how to use code written to solve the React Js Usehistory Push And Pass Props problem.
import {
useHistory
} from "react-router-dom";
const FirstPage = props => {
let history = useHistory();
const someEventHandler = event => {
history.push({
pathname: '/secondpage',
search: '?query=abc',
state: {
detail: 'some_value'
}
});
};
};
export default FirstPage;
Accessing the passed parameter using useLocation from 'react-router-dom':
import {
useEffect
} from "react";
import {
useLocation
} from "react-router-dom";
const SecondPage = props => {
const location = useLocation();
useEffect(() => {
console.log(location.pathname); // result: '/secondpage'
console.log(location.search); // result: '?query=abc'
console.log(location.state.detail); // result: 'some_value'
}, [location]);
};
My preferred way is wrap the Comments component and pass the wrapper as a route handler. react-router - pass props to handler component How to update Pandas from Anaconda and is it possible to use eclipse with this last mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead
I have the following structure for my React.js application using React Router:
var Dashboard = require('./Dashboard');
var Comments = require('./Comments');
var Index = React.createClass({
render: function () {
return (
<div>
<header>Some header</header>
<RouteHandler />
</div>
);
}
});
var routes = (
<Route path="/" handler={Index}>
<Route path="comments" handler={Comments}/>
<DefaultRoute handler={Dashboard}/>
</Route>
);
ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
Since new release, it's possible to pass props directly via the Route
component, without using a Wrapper. For example, by using render
prop.
Component:
class Greeting extends React.Component {
render() {
const {text, match: {params}} = this.props;
const {name} = params;
return (
<React.Fragment>
<h1>Greeting page</h1>
<p>
{text} {name}
</p>
</React.Fragment>
);
}
}
Usage:
<Route path="/greeting/:name" render={(props) => <Greeting text="Hello, " {...props} />} />
If you'd rather not write wrappers, I guess you could do this:
class Index extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<h1>
Index - {this.props.route.foo}
</h1>
);
}
}
var routes = (
<Route path="/" foo="bar" component={Index}/>
);