Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum amount of characters in a div/paragraph tag in react

Tags:

reactjs

I need to add a "read more" link after my paragraph reaches 250 characters..got many solutions using javascript but i am unable to do it with reactjs. Help in any form will be great! thanks Example : text text text texttext texttext texttext texttext texttext texttext texttext text...Read more

like image 798
Rishika Avatar asked Oct 26 '16 06:10

Rishika


1 Answers

If I understand correctly, the difference from what you could see online is that you don't want to show a Read more button if the text has less than 250 characters.

It would be great if you could share what you already have, but just in case, here is a prototype:

class LongText extends Component { 
    state = { showAll: false }
    showMore = () => this.setState({showAll: true}); 
    showLess = () => this.setState({showAll: false});
    render() {
        const {content, limit} = this.props;
        const {showAll} = this.state;
        if(content.length<=limit) {
            // there is nothing more to show
            return <div>{content}<div>
        }
        if(showAll) {
            // We show the extended text and a link to reduce it
            return <div>
                {content}
                <a onClick={this.showLess}>Read less</a>
            </div>
        }
        // In the final case, we show a text with ellipsis and a `Read more` button
        const toShow = content.substring(0,limit)+"...";
        return <div>
            {toShow}
            <span onClick={this.showMore}>Read more</a>
        </div>
    }
}

EDIT: with hooks

const {useState} = React;

const LongText = ({ content,limit}) => {
  const [showAll, setShowAll] = useState(false);

  const showMore = () => setShowAll(true);
  const showLess = () => setShowAll(false);

  if (content.length <= limit) {
    // there is nothing more to show
    return <div>{content}</div>
  }
  if (showAll) {
    // We show the extended text and a link to reduce it
    return <div> 
      {content} 
      <button onClick={showLess}>Read less</button> 
    </div>
  }
  // In the final case, we show a text with ellipsis and a `Read more` button
  const toShow = content.substring(0, limit) + "...";
  return <div> 
    {toShow} 
    <button onClick={showMore}>Read more</button>
  </div>
}


const App = () => <div>
  <LongText content = "Short text" limit = {10}/> 
  <LongText content = "Very long text, very very long" limit = {10} /> 
</div>


ReactDOM.render( <App/>,document.getElementById('react'));
button {
  margin-left: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
like image 82
Christopher Chiche Avatar answered Sep 22 '22 12:09

Christopher Chiche