[Chartjs]-React – Display Chart when button is clicked

2πŸ‘

βœ…

It seems that your approach is slightly incorrect here. The React component maintains its own state. In your case, this state is the content to display. Then, all that your buttons will do is change the value of this state, which triggers a re-render automatically. An example component reworked in this way would look like the following

const contenidoNuevo = "First content"
const contenidoNuevo2 = "Second content"

class App extends React.Component {
  constructor(){
    super();
    this.state = {content: contenidoNuevo}
  }
  
  onClick1 = () => {
        this.setState({content: contenidoNuevo})
  }
  onClick2 = () => {
        this.setState({content: contenidoNuevo2})
  }
  
  render() {
    return (
      <div className="row">
        <button id="btn1" onClick={() => {this.onClick1()}}>
          Option 1
         </button>
      <button id="btn2" onClick={() => {this.onClick2()}}>
        Option 2
     </button>    
     {this.state.content}                                
    </div>
    )
  }
}

You can change the onClick methods to call functions instead of just setting the value, if that better fits your use case.

0πŸ‘

Instead of return component consider do the following:

import React, { Component } from 'react';
class Datas extends Component {
    constructor(props){
        super(props)
        this.state = {
                data: ''
        }
    }
    onClick1 = () => {
        this.setState({ data: <h1>d</h1> });
       
    }
    onClick2 = () => {
        this.setState({ data: <h2>d</h2> });
        
    }
    render() {
        return (
            <div className="row">
                <button id="btn1" onClick={() => { this.onClick1() }}>
                    Option 1
                </button>
                <button id="btn2" onClick={() => { this.onClick2() }}>
                    Option 2
                </button>
                {this.state.data}
            </div >
        )
    }
}
export default Datas;

like this whe you print this state it will change base on the button you press

Leave a comment