Search code examples
reactjsreactstrapreact-button

Reactstrap Button onClick redirection error


Button onClick function in reactstrap is not returning the new page but it the log i have made inside the fuction is working.the problem it seems in the renderData() and handleExam(), where the renderData is supposed to add cards into the page and handleExam() redirect to another page given below with a specific id so that the id can be used to get data from the db.

import React,{ Component } from "react";
import "./Home.css";
import { userService } from '../_service/user.service'; 
import Exam from "./Exam";
import {
  Card,  CardSubtitle, CardText, Col, CardHeader, Row ,Button
} from 'reactstrap';
class Home extends Component {
  constructor(props){
    super(props);
    this.state = {
      isSucess: false,
      arr:[]
    };
  }

  componentDidMount(){
    userService.getExamDetails().then(
      data =>{
            console.log(data)
            this.setState({arr:data})
            this.setState({isSucess:true});
      },
      error => console.log(error)
      )

  }
  examHandle(id){
    console.log(id);
   return (<Exam id={id} />)  }
  renderData(){
   var rendered = this.state.arr.map( (a,index) => {
     return (
    <Col key={a.exam_id} sm="6">
      <Card key={index} className= { "card -"+ a.exam_id } >
    <CardHeader >{a.exam_name}</CardHeader>
    <CardSubtitle>Start Date : {a.start_date}</CardSubtitle>
    <CardSubtitle>End Date : {a.end_date}</CardSubtitle>
    <CardText>{a.is_payed ? "hello World" : "how old are you"}</CardText>
     <Button color='primary' onClick={()=>{this.examHandle(a.exam_id)}}>Button</Button>
    </Card>
    </Col>);
    })
    return <Row sm="6">{rendered}</Row>;
  }
  render(){
  return (
    <div className="Home">
      <div className="lander">
      <div>{this.state.isSucess ?
         this.renderData()

        :
        <h1>No Active Exams</h1>}
      </div>
      </div>
    </div>
  );
}}

export default Home;

The Page i need to display

import React from "react";

const Exam = (props)=>{

    return(
        <div>
            Hello World!!!
    <p>{props.id}</p>
        </div>
    );
}
export default Exam;

I tried calling the function directly onClick() but that too is not working.



Solution

  • You have to know that React will only rerender when there is a state change. There is no use of returning if there is no state change.

    What you can do is learn React-Router which can provide navigation to different components based on user interaction.