I have written below routes in App.js –
JavaScript
x
18
18
1
function App() {
2
return (
3
<>
4
5
<BrowserRouter>
6
<Switch>
7
<Route path="/" exact component={Dashboard} ></Route>
8
<Route path="/details/:index" exact component={ItemDetails} ></Route>
9
<Dashboard></Dashboard>
10
</Switch>
11
12
</BrowserRouter>
13
</>
14
);
15
}
16
17
export default App;
18
I have another component – Items which has Card (Reactstrap). Each card is having a Link –
JavaScript
1
16
16
1
function Items(props) {
2
console.log(props.index.index)
3
return (
4
<Link to={{pathname:"/details",param1:props.index.index}}>
5
<Card tag="a" key={props.index.index} style={{display:'flex',width:'25%',flexWrap:'nowrap',float:'left',cursor: "pointer"}}
6
>
7
<CardBody>
8
<CardTitle> {props.card.card.value} </CardTitle>
9
</CardBody>
10
</Card>
11
</Link>
12
)
13
}
14
15
export default Items
16
Within Link tag , to attribute , I have mentioned –
JavaScript
1
2
1
to={{pathname:"/details",param1:props.index.index}}
2
By this I am expecting , upon clicking of card , component – ItemDetails
should get rendered.
But I cannot see , ItemDetails has got rendered.
Do I need to add anything else within my current code ?
Advertisement
Answer
You can use the useHistory
hook which solve this problem easily
JavaScript
1
22
22
1
import React from 'react'
2
import {useHistory} from 'react-router-dom'
3
function Items({index, card}) {
4
5
const history = useHistory()
6
7
function navigateTo(){
8
history.push(`/details/${index.index}`)
9
}
10
11
return (
12
13
<Card onClick={navigateTo} tag="a" key={props.index.index} style={{display:'flex',width:'25%',flexWrap:'nowrap',float:'left',cursor: "pointer"}}
14
>
15
<CardBody>
16
<CardTitle> {card.card.value} </CardTitle>
17
</CardBody>
18
</Card>
19
)
20
}
21
export default Items
22