0

Hi I am starting to learn react.js

What I want to do is to press the button below

<Button
color="primary"
onClick={this.state.clickMonth}>

The html code will load

clickMonth = () =>{
  this.setState({
  month: <Line data={chartjs.monthLine.data} options= 
  {chartjs.monthLine.options} />
  })
}

however, it doesn't work. I can provide more info if needed. Thank you for your help

Platalea Minor
  • 877
  • 2
  • 9
  • 22

1 Answers1

1

You are code should be something like below.

Event handler functions in react can be called with this.functionName but not this.state.functionName. In your case it should be this.clickMonth but not this.state.clickMonth

Now on clicking the button you are rendering Line component. So to render Line component on button click you can set a boolean flag to true and render the Line component accordingly like how I did below

constructor(props){
  super(props);
  this.state = {
    showLine: false,
    showLine1: false
  }
}
clickMonth = () =>{
  this.setState({
     showLine: true,
     showLine1: false
  })
}

clickYear = () =>{
  this.setState({
     showLine: false,
     showLine1: true
  })
}

render(){
   const { showLine, showLine1 } = this.state;
   return(
     <div>

        {showLine && <Line data={chartjs.monthLine.data} options= 
  {chartjs.monthLine.options} />}
        {showLine1 && <Line data={chartjs.monthLine.data} options= 
  {chartjs.monthLine.options} />}
        <Button color="primary" onClick={this.clickMonth} />
        <Button color="primary" onClick={this.clickYear} />
     </div>
   )
}
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
  • hi, if I also also have quarter and year button. Should I just add clickQuarter, clickYear in the constructor and after render? – Platalea Minor Oct 05 '18 at 07:06
  • @PlataleaMinor Yes. if you want to call different components on different button clicks you should follow that principle. If you want to render the component always then conditional rendering is not required – Hemadri Dasari Oct 05 '18 at 07:08
  • Last question. how to hide the other charts which is irrelevant? right now, when I press on either one, all three charts popup. Thank you in advanced – Platalea Minor Oct 05 '18 at 07:16
  • @PlataleaMinor When the other button clicked make the other two button states to false using setState so that only one component will render for which the button is clicked – Hemadri Dasari Oct 05 '18 at 07:19
  • @PlataleaMinor I updated my answer with differences please have a look – Hemadri Dasari Oct 05 '18 at 07:21
  • Thank you for your answer. Btw, I think it is need to put const { showLine1 } = this.state; too ! Thanks again – Platalea Minor Oct 05 '18 at 07:29
  • @PlataleaMinor Yeah good catch I missed that :) Kindly do upvote as well because you have accepted the answer:) – Hemadri Dasari Oct 05 '18 at 07:35