Skip to content

Instantly share code, notes, and snippets.

@jbrz0
Created August 2, 2020 14:48
Show Gist options
  • Save jbrz0/9d5b9971e445eafde9339df0000488bf to your computer and use it in GitHub Desktop.
Save jbrz0/9d5b9971e445eafde9339df0000488bf to your computer and use it in GitHub Desktop.
useExcerpt: React hook for easy multi line text excerpts
/*
Usage
import {useExcerpt} from '../../hooks/useExcerpt'
1.
Import or store long text in a variable
const text = 'some really long text'
2.
Call the hook
* Add max words parameter! - default is 30
const excerpt = useExcerpt(text, 50)
3.
Use it anywhere in the component
You can also use it directly in a component, ex:
<p>{ useExcerpt(textVariable) }</p>
<p>{ useExcerpt(`long text string`) }</p>
*/
// Hook
export function useExcerpt(text: string, limit: number = 30): string {
// store our input text
let excerpt: string = text
// count our input text, store input text in an array
const amount: number = text.split(' ').filter(n => n != '').length
const words: Array<string> = text.split(' ')
if (amount > limit) {
// limit the words in array, join them back as a string
excerpt = words.slice(0, limit).join(' ') + " ..."
}
return excerpt
}
@jbrz0
Copy link
Author

jbrz0 commented Aug 2, 2020

Usage

Import

import {useExcerpt} from '../../hooks/useExcerpt'
  1. Import or store long text in a variable
const text = 'some really long text'
  1. Call the hook
  • Add max words parameter! - default is 30
const excerpt = useExcerpt(text, 50)
  1. Use it anywhere in the component
    You can also use it directly in a component, ex:
<p>{ useExcerpt(textVariable) }</p>

<p>{ useExcerpt(`long text string`) }</p>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment