Pass props in Link react-router
This line is missing path
:
<Route name="ideas" handler={CreateIdeaView} />
Should be:
<Route name="ideas" path="/:testvalue" handler={CreateIdeaView} />
Given the following Link
(outdated v1):
<Link to="ideas" params={{ testvalue: "hello" }}>Create Idea</Link>
Up to date as of v4/v5:
const backUrl = '/some/other/value'
// this.props.testvalue === "hello"
// Using query
<Link to={{pathname: `/${this.props.testvalue}`, query: {backUrl}}} />
// Using search
<Link to={{pathname: `/${this.props.testvalue}`, search: `?backUrl=${backUrl}`} />
<Link to={`/${this.props.testvalue}?backUrl=${backUrl}`} />
and in the , out dated usage of withRouter(CreateIdeaView)
components render()
withRouter
higher order component:
console.log(this.props.match.params.testvalue, this.props.location.query.backurl)
// output
hello /some/other/value
And in a functional components using the useParams
and useLocation
hooks:
const CreatedIdeaView = () => {
const { testvalue } = useParams();
const { query, search } = useLocation();
console.log(testvalue, query.backUrl, new URLSearchParams(search).get('backUrl'))
return <span>{testvalue} {backurl}</span>
}
From the link that you posted on the docs, towards the bottom of the page:
Given a route like
<Route name="user" path="/users/:userId"/>
Updated code example with some stubbed query examples:
// import React, {Component, Props, ReactDOM} from 'react';
// import {Route, Switch} from 'react-router'; etc etc
// this snippet has it all attached to window since its in browser
const {
BrowserRouter,
Switch,
Route,
Link,
NavLink
} = ReactRouterDOM;
class World extends React.Component {
constructor(props) {
super(props);
console.dir(props);
this.state = {
fromIdeas: props.match.params.WORLD || 'unknown'
}
}
render() {
const { match, location} = this.props;
return (
<React.Fragment>
<h2>{this.state.fromIdeas}</h2>
<span>thing:
{location.query
&& location.query.thing}
</span><br/>
<span>another1:
{location.query
&& location.query.another1
|| 'none for 2 or 3'}
</span>
</React.Fragment>
);
}
}
class Ideas extends React.Component {
constructor(props) {
super(props);
console.dir(props);
this.state = {
fromAppItem: props.location.item,
fromAppId: props.location.id,
nextPage: 'world1',
showWorld2: false
}
}
render() {
return (
<React.Fragment>
<li>item: {this.state.fromAppItem.okay}</li>
<li>id: {this.state.fromAppId}</li>
<li>
<Link
to={{
pathname: `/hello/${this.state.nextPage}`,
query:{thing: 'asdf', another1: 'stuff'}
}}>
Home 1
</Link>
</li>
<li>
<button
onClick={() => this.setState({
nextPage: 'world2',
showWorld2: true})}>
switch 2
</button>
</li>
{this.state.showWorld2
&&
<li>
<Link
to={{
pathname: `/hello/${this.state.nextPage}`,
query:{thing: 'fdsa'}}} >
Home 2
</Link>
</li>
}
<NavLink to="/hello">Home 3</NavLink>
</React.Fragment>
);
}
}
class App extends React.Component {
render() {
return (
<React.Fragment>
<Link to={{
pathname:'/ideas/:id',
id: 222,
item: {
okay: 123
}}}>Ideas</Link>
<Switch>
<Route exact path='/ideas/:id/' component={Ideas}/>
<Route path='/hello/:WORLD?/:thing?' component={World}/>
</Switch>
</React.Fragment>
);
}
}
ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('ideas'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router-dom/4.3.1/react-router-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/4.3.1/react-router.min.js"></script>
<div id="ideas"></div>
pass props to new page via react-router Link
what type of your component functional component
or class component
if you write on functional component you can use useLocation
hooks
from react-router-dom
if you using class component
you should use location
props from your component.
maybe your component be like this, its just example to access state
on location using useLocation
import { useLocation } from "react-router-dom";
const Holes = () => {
const location = useLocation();
return (
<div>
<h1>HOLES</h1>
<h2>{location.state.courseid}</h2>
</div>
);
};
export default Holes;
can't pass props using Link in react router dom
If you are using react-router-dom
v5 then route state is a property on the to
object of the Link
.
RRDv5 Link
<Link to={{ pathname: "/Watch", state: { movie } }}>...</Link>
If using react-router-dom
v6 then state
is a top-level prop.
RRDv6 Link
<Link to="/Watch" state={{ movie }}>...</Link>
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 || {};
React: how to pass props through a Link from react-router-dom?
Link can pass a state object that can be retrieved from you component through location:
import { Link } from "react-router-dom";
const Category = ({ title }) => {
return (
<Link to={{ pathname: "/dishes", state: { title } }}>
{title}
</Link>
);
};
export default Category;
Then you can extract state
from location
prop. But since you are passing this value only when you click on Link
, state
can be undefined if you access the Route
directly. This way you may want to provide a defaultValue
in these cases:
const Dishes = ({location}) => {
const { title = 'defaultValue' } = location.state || {}
return <div>{title}</div>
}
Passing React Router Link to parameter as props
In your App.js class, define your routes first.
function App(prop) {
const {isLoggedIn} = props;
return (
<ThemeProvider theme={theme}>
<BrowserRouter>
<Switch>
<Route exact path='/' component={Bloghome}/>
<Route exact path='/posts/:blogID' component={Blogitem}/>
</Switch>
</BrowserRouter>
</ThemeProvider>
);
}
Now in your Blogitem class, you can read the id as a url parameter.
export default function Blogitem(props) {
const {cat,title,desc}=props;
let { blogID } = useParams();
return (
console.log(blogID);
<>
<div className="blog-item-border">
<img src={person} alt="" className="blog-item-img" />
<div className="blog-item-category">{cat}</div>
<div className="blog-item-title">{title}</div>
<div className="blog-item-desc">
{desc}
</div>
<div className="blog-item-button">
<Link to="/">
<button>Read Post</button>
</Link>
</div>
</div>
</>
);
}
You can pass the Item ID as a URL parameter when you create the link.
<div className="blog-item-button">
<Link to="/posts/001">
<button>Read Post</button>
</Link>
</div>
How to pass method props via link next.js?
You cant pass methods and functions via Link
.
Now, you can use a contexts to share methods/functions/props between pages.
Moreover, if you want to keep some kind of props you can use window storage / cookie.
How to pass props to React component using React Router after state change?
With React-Router, you can pass a state with your navigation call, like so:
...
const navigate = useNavigate();
...
<NavDropdown.Item
key = {i}
id = {score["scoreId"]}
onClick = {(e) => {
navigate('/home/score', { state: {score} });
}}
>
{score["scoreName"]}
</NavDropdown.Item>
Then in ScoreHome.js
const {state} = useLocation();
// state.score <= your selected score
See docs for more
Related Topics
Why Don't We Just Use Element Ids as Identifiers in JavaScript
How to Deal with Big Numbers in JavaScript
Why Doesn't a JavaScript Return Statement Work When the Return Value Is on a New Line
What Do These JavaScript Bitwise Operators Do
Chrome Desktop Notification Example
Check Whether a String Matches a Regex in Js
Check Whether Variable Is Number or String in JavaScript
How to Detect If Browser Window Is Scrolled to Bottom
How to Upload a File with the Js Fetch API
Passing an Array as a Function Parameter in JavaScript
"Innerhtml += ..." VS "Appendchild(Txtnode)"
How to Send JSON Instead of a Query String with $.Ajax
Document.Createelement("Script") Synchronously
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array
Constructor Function VS Factory Functions
Why Was the Arguments.Callee.Caller Property Deprecated in JavaScript