1

I have a scenario like showing text as well adding class togathered. it look like i require to add multiple times with same elements nearly. what would be the correct approach for this kind of scenarios?

here is my template:

<span><a className={this.state.showMore ? 'active' : ''} onClick={this.showMore}>{this.state.showMore ? 'read less' : 'read more'}</a></span>

i have added the state showMore both a tag and the text inside. is there any simple way to handle same conditions across page?

Thanks in advance.

3gwebtrain
  • 14,640
  • 25
  • 121
  • 247

2 Answers2

4

I'd create a component to handle read-more, and pass the props from where it's used if there's any, So same functionality is same across my application and if there's any improvements I can handle by it in one single place.

here is a demo

EX: functional component

export const ReadMore = ({ text, truncateLength = 10 }) => {
  const [showMore, setShowMore] = useState(false);

  const getText = () => {
    if (showMore) {
      return text;
    }

    const truncatedText = text.substring(0, truncateLength);
    if (text.length > truncateLength) {
      return `${truncatedText}...`;
    }

    return truncatedText;
  };

  return (
    <span>
      {getText()} &nbsp;
      <a
        className={showMore ? "active" : ""}
        onClick={() => setShowMore(!showMore)}
      >
        {text.length > truncateLength && (showMore ? "read less" : "read more")}
      </a>
    </span>
  );
};

and use it like this props could be:

  • text: is the text that should be read-less or more.

  • truncateLength: is the length that should show if the text length is greater, and optional prop, if this isn't provided ReadMore component will set the value to 10 by default, (check the props of ReadMore)

<ReadMore
    text="this is the text that should do the react-more and read-less"
    truncateLength={10}
/>
Kalhan.Toress
  • 21,683
  • 8
  • 68
  • 92
1
{this.state.showmore ? 
<span><a className={'active'} onClick={this.showMore}>read less</a></span> 
:
<span><a onClick={this.showMore}>read more</a></span>
}

should be a more readable and clearer way of doing this. Basically when you have >1 thing depending on the same condition, take the condition outside would be my way to go!

Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35