0

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>

1 Answer 1

1

<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 ;)

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.