Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Trigger onClick function from within conditional content

I'm using the following code. Inside the ContentTwo component, there is a button, I want it to be able to trigger the same function as the button in the render, when it is the live content. How would I go about this?

class Toggle extends React.Component {
   constructor(props) {
     super(props);
     this.state = {isToggleOn: true};

      // This binding is necessary to make `this` work in the callback
     this.handleClick = this.handleClick.bind(this);
     }

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

    render() {
        return (
             <div >
                 {this.state.isToggleOn ? <ContentOne /> : <ContentTwo />}
                 <button onClick={this.handleClick}>Swap</button>
             </div>
         );
     }
     }
     function ContentOne(props) {
         return(<h1>Content One</h1>
          );
     }

     function ContentTwo(props) {
          return(<button onClick={this.handleClick}>Swap like the other button</button>
          );
     }

      ReactDOM.render(
             <Toggle />,
             document.getElementById('root')
      );
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You could pass the this.handleClick to ContentTwo and access it from the props:

 <ContentTwo handleClick={this.handleCLick} />

and then

 function ContentTwo(props) {
      return(<button onClick={props.handleClick}>Swap like the other button</button>
      );
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!