0

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

2
  • 2
    You're not calling handleSwitch in your onClick handlers, you're just returning the function. {() => handleSwitch()} or {handleSwitch} is what you need. Commented Mar 31, 2019 at 12:53
  • 1
    It should beonClick={() => handleSwitch()} and remove this.handleSwitch = this.handleSwitch.bind(this); Commented Mar 31, 2019 at 12:54

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.