Doe
Doe

Reputation: 163

No function call - onclick doesn't work react

I have two components. The first of them looks like this

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      change: false
    };

    this.handleSwitch = this.handleSwitch.bind(this);
  }

  handleSwitch = () => {
    const { change } = this.state;
    this.setState({ change: !change })
    console.log(this.state.change)
  }

  render() {
    const { change } = this.state;

    return (
      <>
        <UserProfilPanel handleSwitch={this.handleSwitch}/>
        {
          change ? <UserProfilGallery /> : <UserProfilContent />
        }
      </>
    );
  }
}

To the UserProfile Panel component, it passes the function which is to be responsible for changing the state.

const UserProfil = (handleSwitch) => {
  return (
    <Container>
      <div>
        <button onClick={() => handleSwitch}>
          gallery
        </button>
        <button onClick={() => handleSwitch}>
          info
        </button>
      </div>
    </Container>
  )
}

When I press some buttons, nothing happens. The console also does not appear an error.

How to fix this problem? I want to change content after clicking the button

Upvotes: 0

Views: 1174

Answers (1)

charlietfl
charlietfl

Reputation: 171700

First argument in UserProfil() is props. To destructure only a specific property of the props object you need to do:

const UserProfil = ({handleSwitch}) => {...

Then inside your onClick anonymous function you need to call handleSwitch()

<button onClick={() => handleSwitch()}>
                           //      ^^  call function

Upvotes: 4

Related Questions