Matthis Kohli
Matthis Kohli

Reputation: 1995

How to trigger Reactjs onClick inside render instead of return?

How can I assign an onClick function if I decide to do a conditional render outside of React return?

Stackoverflow wants me to add even more description than the one I provided but my spent 1 hour writing code into their editor without syntax help or eslint :D

section:hover {
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"/>

<script type="text/babel">

const RotateOnClick = ( {rotated, handleChange} ) => {
  if (rotated) {
    return <section onClick={handleChange}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={handleChange}>I'm not rotated. Click me to rotate!</section>  
  }
}

class Rotator extends React.Component {

  // Change state to true to see that it renders if toggled
  state = {
    isRotated: false
  }
  
  toggleRotation = () => {
    // Outdated initial code when asking the question
    // console.log("React doesn't like me. It will never call me :( ")

    console.log("Yei, it works! React likes me again")
    const { isRotated } = this.state
    this.setState( {isRotated: !isRotated })
  }
    
  render() {
    const { isRotated } = this.state
    
    let conditionalRender;    
    if (isRotated) {
      conditionalRender = <RotateOnClick rotated handleChange={this.toggleRotation} />
    } else {
      conditionalRender = <RotateOnClick handleChange={this.toggleRotation} />
    }
  
    return (
    <div className="hover">
      {conditionalRender}
    </div>
    );
  }
}

ReactDOM.render(
    <Rotator />,
    document.getElementById('root')
);
</script>

Upvotes: 0

Views: 72

Answers (1)

xadm
xadm

Reputation: 8418

<RotateOnClick rotated onClick={this.toggleRotation} />

doesn't mean that component will react to click event. You can't assign event handlers to components!

You should pass handler to component, f.e.

<RotateOnClick rotated clickHandler={this.toggleRotation} />

and use this prop in render:

const RotateOnClick = ( {rotated, clickHandler} ) => {
  if (rotated) {
    return <section onClick={clickHandler}>I'M ROTATED! Click me to rotate again!</section>
  } else {
    return <section onClick={clickHandler}>I'm not rotated. Click me to rotate!</section>  
  }
}

This way react should be nice again ;)

Upvotes: 1

Related Questions