const [ showAll, setShowAll ] = useState(false);
const defaultShow = 2;
const showAllByDefault = ingredients.length <= defaultShow;
const ingredientsToShow = (showAll || showAllByDefault)
? ingredients
: ingredients.slice(0, defaultShow);
{showAllByDefault
? null
: <button onClick={() => setShowAll(val => !val)}>{showAll ? 'hide' : 'show'}</button>
}
<ul>
{ingredientsToShow.map(n => <li>{n}</li>)}
</ul>
import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
constructor (props){
super(props);
this.state = {isExpanded: false};
this.handleShowClick = this.handleShowClick.bind(this);
this.handleHideClick = this.handleHideClick.bind(this);
}
handleShowClick() {
this.setState({isExpanded: true});
}
handleHideClick() {
this.setState({isExpanded: false});
}
render() {
const isExpanded = this.state.isExpanded;
let button;
if (isExpanded) {
button = <button onClick={this.handleHideClick} > hide</button>;
} else {
button = <button onClick={this.handleShowClick}> show</button>;
}
return (
<div>
{button}
<ul>
<li >1</li>
<li >2</li>
{isExpanded &&
<>
<li >3</li>
<li >4</li>
<li >5</li>
</>
}
</ul>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('container')
);