2

I'm trying to accomplish read more feature in css3, ES6 and React.

I have a very long description (this comes from the server so it's dynamic) and I would like to add 'read more' feature in this. If a description is more than 3 lines then a button/link should could us as 'read more' and when I click that button then rest of the description should be displayed.

This is my code:

React:

<div className="content">

Description of the product 

<button onClick=(() => {})>Read more</button>

</div>

CSS:

.content{
overflow: hidden;
line-height: 1.2em;
height: 3.6em;
}

What I am not able to figure out is when I click 'read more' button then how can change div id to make it's height to auto. I have the javascript code but I want to implement this in ES6

JS:

document.querySelector('button').addEventListener('click', function() 
{
  document.querySelector('#content').style.height= 'auto';
this.style.display= 'none';
});

Any help is highly appreciated!

1 Answer 1

5

I created a fiddle for you here: https://jsfiddle.net/jwm6k66c/3063/. You want to avoid directly manipulating dom when using React. The preferred approach would be to use component state to toggle classes on the content div.

class App extends React.Component {
    constructor(){
    this.description = getDescription();
    this.state = {
        expanded: false
    }
  }
    render(){
    const { expanded } = this.state;
    const toggledClass = expanded ? 'expanded' : 'collapsed';
    return(
      <div>
        <div className={`content ${toggledClass}`}>
            {this.description}
        </div>
        <button onClick={() => this.setState({ expanded: !expanded })}>
            {expanded ? 'View Less' : 'View More'}
        </button>
      </div>
    )
  }
}

CSS

.content {
  overflow: hidden;
  line-height: 1.2em;
  height: 3.6em;
}
.content.collapsed{
  overflow: hidden;
}
.content.expanded{
  overflow: visible;
  height: auto;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you so much for your help! I really appreciated that. Would it be possible to do this in ES6 only?
Yeah that's all es6. What is not es6?
I was wondering whether I can do this using only ES6 and not using react state or anything else.
I guess that's up to you to refactor that out, but at that point you probably shouldn't even be using React.
seems like if the text is upto 3 lines then also 'view more' button is showing up. How can I make it invisible if the text is 3 lines and visible more than 3 lines?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.