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!

jackysatpal
  • 319
  • 1
  • 6
  • 16

1 Answers1

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;
}
Chase DeAnda
  • 15,963
  • 3
  • 30
  • 41
  • Thank you so much for your help! I really appreciated that. Would it be possible to do this in ES6 only? – jackysatpal Jun 28 '17 at 17:33
  • Yeah that's all es6. What is not es6? – Chase DeAnda Jun 28 '17 at 17:37
  • I was wondering whether I can do this using only ES6 and not using react state or anything else. – jackysatpal Jun 28 '17 at 17:44
  • 1
    I guess that's up to you to refactor that out, but at that point you probably shouldn't even be using React. – Chase DeAnda Jun 28 '17 at 17:49
  • 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? – jackysatpal Jul 05 '17 at 20:22
  • You'll have to write your own JS to figure out when the div has overflow or not. Check out this post for some help: https://stackoverflow.com/questions/7668636/check-with-jquery-if-div-has-overflowing-elements – Chase DeAnda Jul 05 '17 at 21:21