I'm having trouble deciding the difference between these two patterns of rendering in React. Hopefully someone can shed some light on this matter.
Pattern 1: React's Conditional Render
https://facebook.github.io/react/docs/conditional-rendering.html
class List extends React.Component {
state = {
menu: false,
}
handleMouseOver = () => {
this.setState({
menu: true
});
}
handleMouseLeave = () => {
this.setState({
menu: false
});
}
render() {
const { menu } = this.state;
return (
<li
onMouseOver={this.handleMouseOver}
onMouseLeave={this.handleMouseLeave}
>
{menu && <Menu />}
</li>
);
}
}
Pattern 2: display: none
.menu {
display: none;
}
.li:hover .menu {
display: block;
}
const List = () => (
<li className="li"><Menu className="menu"/></li>
);
Question:
If I need to render 100 of these items in a single page, which pattern should I go for?
How can I determine which pattern is better?
Are there any performance benefit of using one over the other?
In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application. Conditional rendering in React works the same way conditions work in JavaScript.
The ReactDOM. render() function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element.
Logical && Operator Another way to conditionally render a React component is by using the && operator.
I tend to use display: none
in situations where there's a simple condition to show something (e.g hover, etc).
If it's a bit more complex (e.g. click a checkbox to hide an element) then I go with conditional rendering.
The reason behind this is that I don't want to cause state changes and trigger an update for something as trivial as a hover state, and don't want to fiddle around with obscure css classes for things that will have to involve code anyway.
Again, this is my personal preference.
TL;DR: CSS if super simple (e.g. hover), conditional render if more logic involved
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With