1.2.4 • Published 1 year ago

react-hook-use-read-more v1.2.4

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

react-hook-use-read-more 📖

Code for read more buttons can get cumbersome when there is some conditional string splitting and slicing involved. I couldn't find any open source hooks that would take care of it so there it is. React hook for quick and elegant use in read more buttons! Enjoy 🤗

Installation

Install it with npm:

npm i react-hook-use-read-more

Or with yarn:

yarn add react-hook-use-read-more

Usage

const { firstPart, secondPart } = useReadMore("Lorem ipsum dolor sit amet")
useReadMore(text: string, config?: Config)
type Config = {
  treshold?: number
  firstPartMaxLength?: number
}

Basic

import React, { useState } from "react"
import useReadMore from "react-hook-use-read-more"

const Component: React.FC = () => {
  const { firstPart, secondPart
  } = useReadMore("Hello world foo bar")

  const [showMore, setShowMore
  ] = useState<boolean>(false)

  const handleClick = () => {
    setShowMore(!showMore)
  }

  return (
    <p>
      // Hello world   
      {firstPart}

      <button onClick={handleClick}>Show more</button>

      // foo bar
      {showMore ? secondPart : ""}
    </p>
  );
};

export default Component

Custom treshold

import React, { useState } from "react"
import useReadMore from "react-hook-use-read-more"

const Component: React.FC = () => {
  const { firstPart, secondPart
  } = useReadMore("Hello world foo bar", {
      // Translates to treshold at 25%   
      treshold: 25
    })

  const [showMore, setShowMore
  ] = useState<boolean>(false)

  const handleClick = () => {
    setShowMore(!showMore)
  }

  return (
    <p>
      // Hello
      {firstPart}

      <button onClick={handleClick}>Show more</button>

      // world foo bar
      {showMore ? secondPart : ""}
    </p>
  );
};

export default Component

Custom firstPartMaxLength

import React, { useState } from "react"
import useReadMore from "react-hook-use-read-more"

const Component: React.FC = () => {
  const { firstPart, secondPart
  } = useReadMore("Banana apple pear peach strawberry raspberry", {
      firstPartMaxLength: 2
    })

  const [showMore, setShowMore
  ] = useState<boolean>(false)

  const handleClick = () => {
    setShowMore(!showMore)
  }

  return (
    <p>
      // Banana apple
      {firstPart}

      <button onClick={handleClick}>Show more</button>

      // pear peach strawberry raspberry
      {showMore ? secondPart : ""}
    </p>
  );
};

export default Component
1.2.4

1 year ago

1.2.3

1 year ago

1.2.2

2 years ago

1.2.1

2 years ago

1.2.0

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago

0.1.0

2 years ago