How can I conditionally render JSX?
// Approach1
const FullName = (props) => {
const { firstName, lastName, title } = props
// Elided code...
}
const NameHolder = (props) => {
const { firstName, lastName, title } = props
// High Complexity (Imperative Style)
return ({ firstName && lastName && title && <FullName {...{firstName, lastName, title }}/> })
}
// Approach2
const FullName = (props) => {
const { firstName, lastName, title } = props
// Elided code...
}
const NameHolder = (props) => {
const { firstName, lastName, title } = props
const isVisible = (firstName && lastName && title)
// Medium Complexity (Hybrid Style)
return ({ isVisible && <FullName {...{firstName, lastName, title }}/> })
}
// Approach3
const FullName = (props) => {
const { firstName, lastName, title, isVisible } = props
if (!isVisible) return null
// Elided code...
}
const NameHolder = (props) => {
const { firstName, lastName, title } = props
const isVisible = (firstName && lastName && title)
// Low Complexity (Declarative Style)
return (<FullName {...{firstName, lastName, title, isVisible }}/>)
}
PreviousHow can I DRY-up passing props to a React component?NextWhat are the different types of PropTypes I can use?
Last updated
Was this helpful?