Skip to content
Advertisement

React Route not navigating

I have written below routes in App.js –

function App() {
  return (
    <>
    
   <BrowserRouter>
    <Switch>
      <Route path="/" exact component={Dashboard} ></Route>
      <Route path="/details/:index" exact component={ItemDetails} ></Route>
      <Dashboard></Dashboard>
      </Switch>
     
     </BrowserRouter>
    </>
  );
}

export default App;

I have another component – Items which has Card (Reactstrap). Each card is having a Link –

function Items(props) {
    console.log(props.index.index)
    return (
        <Link to={{pathname:"/details",param1:props.index.index}}>
        <Card tag="a" key={props.index.index} style={{display:'flex',width:'25%',flexWrap:'nowrap',float:'left',cursor: "pointer"}} 
          >
        <CardBody>
            <CardTitle> {props.card.card.value} </CardTitle>
        </CardBody>
    </Card>
    </Link>
    )
}

export default Items

Within Link tag , to attribute , I have mentioned –

to={{pathname:"/details",param1:props.index.index}}

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

import React from 'react'
import {useHistory} from 'react-router-dom'
function Items({index, card}) {

    const history = useHistory()

    function navigateTo(){
        history.push(`/details/${index.index}`)
    }

    return (
 
        <Card onClick={navigateTo} tag="a" key={props.index.index} style={{display:'flex',width:'25%',flexWrap:'nowrap',float:'left',cursor: "pointer"}} 
          >
        <CardBody>
            <CardTitle> {card.card.value} </CardTitle>
        </CardBody>
    </Card>
    )
}
export default Items
Advertisement