I've found myself doing a lot of if-else conditions in React recently, but not actually needed anything on the else:
{node.tags ?
<div className="tags"> {
node.tags.map(e =>
<p key={e}>{e}</p>
)}
</div> :
<></>
}
Is there a cleaner way of doing this, or is it the standard?
I was thinking about doing it in a function - but I'm not sure what alternatives there are:
const getTags = (node) => {
if (!node.tags) {
return;
}
return (
<div className="tags"> {
node.tags.map(e =>
<p key={e}>{e}</p>
)}
</div>
)
}
In most cases, you can simplify this to:
{node.tags &&
<div className="tags"> {
node.tags.map(e =>
<p key={e}>{e}</p>
)}
</div>
}
I like to use &&
for this purpose as the following:
{
node.tags &&
<div className="tags">
{
node.tags.map(e => <p key={e}>{e}</p>)
}
</div>
}
You can read more about &&
at Conditional Rendering documentation. Especially the Inline If with Logical && Operator section which states:
You may embed expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical
&&
operator. It can be handy for conditionally including an element.
I usually create a ShowHide
component for all conditionals and a map-function
for Arrays
:
const ShowHide = ({show, children}) => show && children const Tag = ({tag}) => <p>{tag}</p> const mapTagsToJSX = tags => tags && tags.map(tag => (<Tag key={tag} tag={tag} />)) const Tags = ({tags}) => ( <div> <ShowHide show={tags}> {mapTagsToJSX(tags)} </ShowHide> <ShowHide show={!tags}> loading tags... </ShowHide> </div> ) const useTags = () => { const [tags, setTags] = React.useState(null) React.useEffect(() => { setTimeout(() => { setTags([1,2,3]) }, 1000) }, []) return tags; } const App = () => { const tags = useTags() return (<Tags tags={tags}/>) } const root = document.getElementById('root'); ReactDOM.render(<App />, root)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script> <div id="root"></div>
Good Luck...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.