I have a div with many <p>
and <span>
inside, is there any example of how to create a show more/less button with ReactJS to adjust the size of a div?
I have tried to install npm read more and npm truncate, but it seems not to solve my problem. Because I have to adjust the size of a div and the text in the button on click in React.
Thanks!
With React you can easily adapt the rendering of your component depending on the state. You can have a boolean in the state (isOpen
for example) and toggle the value when you click on the more/less button.
After that, you have just to render X items and change the button text depending on the boolean value.
I made an exemple with datas stored inside an array, but you could easily adapt to your case.
const MAX_ITEMS = 3;
class MoreLessExample extends React.Component{
componentWillMount() {
this.state = {
isOpen: false,
};
this.items = [
'Item 1',
'Item 2',
'Item 3',
'Item 4',
'Item 5',
'Item 6',
];
}
toggle = () => {
this.setState({ isOpen: !this.state.isOpen });
}
getRenderedItems() {
if (this.state.isOpen) {
return this.items;
}
return this.items.slice(0, MAX_ITEMS);
}
render() {
return(
<div>
{this.getRenderedItems().map((item, id) => (
<div key={id}>{item}</div>
))}
<button onClick={this.toggle}>
{this.state.isOpen ? 'less' : 'more'}
</button>
</div>
);
}
}
ReactDOM.render(<MoreLessExample />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Here's a Material UI answer:
import { Button, makeStyles } from "@material-ui/core";
import React, { useState } from "react";
const useStyles = makeStyles((theme) => ({
hidden: {
display: "-webkit-box",
WebkitLineClamp: 4,
overflow: "hidden",
WebkitBoxOrient: "vertical"
}
}));
function ReadMore({ children }) {
const classes = useStyles();
const [isHidden, setIsHidden] = useState(true);
return (
<>
<div className={isHidden ? classes.hidden : null}>{children}</div>
<Button size="small" onClick={() => setIsHidden(!isHidden)}>
{isHidden ? "⬇ More" : "⬆ Less"}
</Button>
</>
);
}
export default ReadMore;
And Implement it like this:
<ReadMore>
<Typography>
Hey World, what's up
</Typography>
</ReadMore>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With