reactjs

React-router Link Changes URL ID but Component Does Not Reload


I use Link to redirect a list of items to another detail component. But now the URL changes with the selected IDs but the detail component does not called. Please help with my react-router issue. Below is my code:

```
index.js
 <BrowserRouter>
   <Switch>
      <Route path='/' component={App} />
      <Route path='/course/:ID' component={CourseDetail} />
   </Switch>
</BrowserRouter>

  CourseList.js
    
           
            const CourseList=({Courses})=>{
             //map list
            const renderedList= Courses.map(course=>{
                return (<div>
            
                <div class="content">
                <Link  to={{ pathname: 'course/'+course.ID}}                    
                                    key={course.ID}>
                                    View More
                                </Link>    
                </div>
                </div> 
            )
            });
            return (
            <Router><div>
                {renderedList}
                <Route path="course/:ID" component={CourseDetail} />
            </div></Router>);
            }
            export default CourseList;
        
CourseDetail.js

           
            class CourseDetail extends Component {
              state={
                 ID: this.props.match.params.ID,
                 course:null};
                componentDidMount(){
                 //this.runSearch only get called when URL loads, but not when Link        //clicked
                  this.runSearch();
                
               }
              
               runSearch=async()=>{
             
                 const response= await axios.get('API\?{this.props.match.params.ID}')
                 this.setState({course: response.data});
              
               }
            render(){
               //course is null below
            //const course=this.state.course;
           
            return (
               <div>
                Course Detail: ID {this.props.match.params.ID}
            </div>
            ); }   
            };
            export default withRouter(CourseDetail);


Solution

  • You need to specify the attribute exact for your indexRoute, otherwise for even /course/:ID route it will still match with / .

    Can you please update your index.js file as below.

     <BrowserRouter>
       <Switch>
          <Route exact path='/' component={App} />
          <Route path='/course/:ID' component={CourseDetail} />
       </Switch>
    </BrowserRouter>
    

    Hope this will work for you!