Skip to content
This repository has been archived by the owner on Jun 5, 2023. It is now read-only.

Commit

Permalink
feat: New component ViewMoreText
Browse files Browse the repository at this point in the history
  • Loading branch information
diondiondion committed Aug 30, 2019
1 parent 3733b74 commit 0f78209
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/ViewMoreText/README.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
name: ViewMoreText
menu: Components
---

import {Playground, Props} from 'docz';

import InlineList from '../InlineList';
import ViewMoreText from './';

# ViewMoreText

Truncates a piece of text by a specified amount and displays a "View more" button at the end of it, which will reveal the rest of the text when clicked.

The labels of the "View more" and "View less" buttons can be customised using the props `viewMoreLabel` and `viewLessLabel`.

## Examples

<Playground>
<ViewMoreText
content="This is a short example text with a disappointing reveal."
truncateBy={26}
/>
<br />
<br />
<ViewMoreText
content="Here comes a longer, tastier example. Beetroot water spinach okra water chestnut ricebean pea catsear courgette summer purslane. Water spinach arugula pea tatsoi aubergine spring onion bush tomato kale radicchio turnip chicory salsify pea sprouts fava bean. Dandelion zucchini burdock yarrow chickpea dandelion sorrel courgette turnip greens tigernut soybean radish artichoke wattle seed endive groundnut broccoli arugula."
truncateBy={150}
viewMoreLabel="Read more"
viewLessLabel="I don't care about any of that"
/>
</Playground>

## Props

<Props of={ViewMoreText} />
42 changes: 42 additions & 0 deletions src/ViewMoreText/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import React, {Fragment, useState} from 'react';
import PropTypes from 'prop-types';

import truncateText from '../utils/truncateText';
import TextLink from '../TextLink';

function ViewMoreText(props) {
const {
content,
truncateBy = 110,
viewMoreLabel = 'View more',
viewLessLabel = 'View less',
} = props;

const [showMore, setShowmore] = useState(false);

function toggleShowMore() {
setShowmore(prevState => !prevState);
}

const shouldTextBeTruncated = content && content.length > truncateBy;

return (
<Fragment>
{truncateText(content, showMore ? null : truncateBy)}{' '}
{shouldTextBeTruncated && (
<TextLink as="button" onClick={toggleShowMore}>
{showMore ? viewLessLabel : viewMoreLabel}
</TextLink>
)}
</Fragment>
);
}

ViewMoreText.propTypes = {
content: PropTypes.string.isRequired,
truncateBy: PropTypes.number,
viewMoreLabel: PropTypes.string,
viewLessLabel: PropTypes.string,
};

export default ViewMoreText;

0 comments on commit 0f78209

Please sign in to comment.