react-router - pass props to handler component
UPDATE
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} />} />
Codesandbox Example
OLD VERSION
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);
});
How to pass props to component with NavLink
In the new version, the state is passed as a separate prop. Try using
<NavLink to={{pathname :"/wind"}}
state={{from: "This is my props"}} >Wind</NavLink>
And the component try fetching like this
import React from "react";
import { useLocation } from "react-router-dom";
const Wind = () => {
const location = useLocation();
const { state } = location;
console.log(state.from);
return (
<div className="Wind">
<h1>Wind</h1>
</div>
);
};
export default Wind;
How to pass props within components with react-router v6
When you send state in the route transition it isn't sent via props, but rather it's sent via the routing context. In the EditUser
component you can access the sent route state via the location
object returned from the useLocation
hook.
Example:
import { useLocation } from 'react-router-dom';
...
const location = useLocation();
const { state } = location;
const { user } = state || {};
How to pass props using react router link v6?
The generateQuestion
callback is asynchronous, so you won't be able to send data in route state via the Link
, but what you can do is move the onClick
handler to the Link
and call event.preventDefault
on the click
event to prevent the navigation action, and issue an imperative navigation after the questions have been fetched.
Example:
import { Link, useNavigate } = 'react-router-dom';
...
const navigate = useNavigate();
...
generateQuestions = async (event) => {
event.preventDefault();
try {
const data = await questionsData();
const arrData = data.map(element => ({
...element,
id: nanoid(),
}));
navigate("/quiz", { state: { questions: arrData } });
} catch(error) {
// handle rejected Promise/error/etc...
}
}
...
<Link to="/quiz" onClick={generateQuestions}>
<button type="button">
Start Quiz
</button>
</Link>
...
In the Quiz
component use the useLocation
hook to access the passed route state.
import { useLocation } from 'react-router-dom';
...
const { state } = useLocation();
const { questions } = state || {};
In React router dom can i pass a props in a Link?
Using state
prop you can as below
Using React Router - V5
Docs ref for Link - V5
function App(){
const test = "Hello"
return(
<Link to= {{ pathname : "/detail", state: { test: "dummy"} }}> detail </Link>
)
}
Using React Router - V6
Docs ref for Link - V6
function App(){
const test = "Hello"
return(
<Link to= "/detail" state= {{ test: "dummy" }} > detail </Link>
)
}
and get the value using useLocation
hook which is same in V5 & V6
In my detail component I can call like this.
function detail(){
const {state} = useLocation();
return(
<p>{state.test}</p>
)
}
Related Topics
Socket.Io 1.X: Use Websockets Only
Typescript: Deep Keyof of a Nested Object, with Related Type
Why Not Always Use the Index as the Key in a Vue.Js for Loop
JSON Stringify Changes Time of Date Because of Utc
Switch Statement for String Matching in JavaScript
Cross Domain Post Request Is Not Sending Cookie Ajax Jquery
JavaScript Fuzzy Search That Makes Sense
Remembering State Before App Goes in Foreground
How to Select a Value in a Select Dropdown with JavaScript
Adding Prototype to JavaScript Object Literal
The Preferred Way of Creating a New Element with Jquery
Property 'Value' Does Not Exist on Type Eventtarget in Typescript
Function to Calculate Distance Between Two Coordinates
Disabling the Long-Running-Script Message in Internet Explorer
Refused to Execute a JavaScript Script. Source Code of Script Found Within Request
Logging Clientside JavaScript Errors on Server
Auto-Refreshing Div with Jquery - Settimeout or Another Method