EN
React / react-router - pass props to a child component using Router
0 points
In this article, we would like to show you how to pass props to a child component using React Router.
Below we create MyComponent
that receives props via Route
element's render()
method.
Then, we simply use props.data
to access the props.
Practical example:
xxxxxxxxxx
1
import React from 'react';
2
import { BrowserRouter as Router, Route } from 'react-router-dom';
3
4
const MyComponent = (props) => (
5
<h2>
6
{props.data.map((fruit) => (
7
<li key={fruit}>{fruit},</li>
8
))}
9
</h2>
10
);
11
12
const App = () => {
13
const fruits = ['🍏 Apple', '🍌 Banana', '🍒 Cherry'];
14
15
return (
16
<Router>
17
<Route path="/" render={() => <MyComponent data={fruits} />} />
18
</Router>
19
);
20
};
21
22
export default App;
You can run this example here.