Search code examples
reactjsuse-effectuse-state

Display state.joke when toggle button is only ON


Im trying to make it so that the joke will display only when the toggle button is 'ON'. Right now I have the joke displaying all the time and not sure where I should go from here. Should I be using useEffect and how?

import React from 'react';
import axios from "axios";

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    this.jokes = "https://icanhazdadjoke.com/"
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  async componentDidMount() {
    const url = "https://icanhazdadjoke.com/"
    let result = null;
    try {
      result = await axios.get(url, {
        headers: {
          Accept: "application/json"
        }
      })
    } catch(e) {
      console.log(e);
    }
    this.setState({jokes: result.data.joke});
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>
          {this.state.isToggleOn ? 'ON' : 'OFF'}
        </button>
        <p>
> This displays the joke and changes when page is refreashed
          {this.state.jokes}
        </p>
      </div>
    );
  }
}

export default Toggle;

Solution

  • you can do it this way:

    {this.state.isToggleOn && <p> {this.state.jokes} </p>
    

    it only shows the joke when the toggle is on.