Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use "this" in a JSX rendered html element?

My question is about conditionally rendering in JSX & the use of this.

Consider the following code in my React application:

render() {
    return (
        <li onMouseEnter={this.mouseEnter}>
          //things
        </li>
      )
    }

I would like to conditionally render the onMouseEnter attribute so that it doesn't get applied every time the component gets called and displays the <li> tag.

For example:

render() {
    return (
        <li {this.renderMouseEvents()} >
          ...
        </li>
      )
    }

But visual studio complains and says that "[js] "..." expected"

Obviously calling { this.renderMouseEvents() } outside the HTML element accepts the use of this.

Why is this not valid inside an html element in JSX?

What is a proper/cleaner way to accomplish this conditional rendering in JSX?

Any help is appreciated, thanks!

like image 520
lsimonetti Avatar asked Oct 20 '25 10:10

lsimonetti


1 Answers

Just insert your conditional into the attribute:

import noop from 'lodash/noop';

render() {
    return (
        <li onMouseEnter={ifSatisfies ? this.mouseEnter : noop}>
          //things
        </li>
      )
    }
like image 165
Denialos Avatar answered Oct 21 '25 22:10

Denialos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!