'How can conditionally render items in functional component?
I have the following code
export default function Autocomplete() {
return (
<div className="wrapper" >
<div className={ isLoading ? 'is-loading control' : 'control' } >
<input type="text" className="input" onChange={onInputClick}/>
</div>
{
<div className="list is-hoverable">
{response.map(item => {
return <a className="list-item">{item}</a>
})}
</div>
}
</div>
);
}
how can I conditionally check if the response - so response. length is equal to zero then I should not render this part
<div className="list is-hoverable">
{response.map(item => {
return <a className="list-item">{item}</a>
})}
Solution 1:[1]
export default function Autocomplete() {
return (
<div className="wrapper">
<div className={isLoading ? "is-loading control" : "control"}>
<input type="text" className="input" onChange={onInputClick} />
</div>
{response.length > 0 && (
<div className="list is-hoverable">
{response.map(item => {
return <a className="list-item">{item}</a>;
})}
</div>
)}
</div>
);
}
You can do response.length > 0 && (<div>......</div>)
Solution 2:[2]
you need to use conditional rendering using the condition ? true : false or && operator
return (
<div className="wrapper" >
<div className={ isLoading ? 'is-loading control' : 'control' } >
<input type="text" className="input" onChange={onInputClick}/>
</div>
{
<div className="list is-hoverable">
{response.length && response.map(item => {
return <a className="list-item">{item}</a>
})}
</div>
}
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kevin |
| Solution 2 |
