Reputation: 299
I was wondering how you structure your React code. I was writing a simple component, and while I wrote a lot of similar ones, this time I thought about two possibilities.
{this.state.scrollY > 200 ?
<div className={style.MobileMenu}>
<FontAwesomeIcon icon={faBars} />
</div> :
null
}
This renders a div if the value stored in the state for the scrollY property is more than 200. Fine, but if I have many more conditional renderings in my component I feel that this could lead to unreadable code. So my real question is if it might be better to delegate the render logic for that part of the UI to a stateless component like that:
import React from 'react';
export default ({scrollY}) => (
{scrollY > 200 ?
<div className={style.MobileMenu}>
<FontAwesomeIcon icon={faBars} />
</div> :
null
}
);
Then just import that component in its parent. Is it common knowledge, is it useful?
Thanks
Upvotes: 0
Views: 984
Reputation: 4059
That is totally fine. What I usually do is that I will offload this to a different function within my component itself (unless it needs to be reused across multiple components, in which case I would definitely go with what you suggested in your question) with a name prefixed with 'render'. Like this :
export default class MyComponent extends Component {
renderSomethingAwesome() {
const {scrollY} = this.props;
return {
scrollY > 200 ?
<div className={style.MobileMenu}>
...
</div> :
null
}
}
render () {
return <div>
{this.renderSomethingAwesome()}
</div>
}
}
In the above example I am using a class method, but you can also make it a static function and instead of accessing the props directly you can pass it from the render function itself
Upvotes: 2