Approach 2 Using the useHighlight hook
In this approach, we will use the useHighlight hook. This hook is used when we want to use the same type of highlights at many places. This helps us to write less redundant code. Project structure and setup is going to be same for this approach. We will change the contents of the HightlightExample.js file.
Javascript
import React from "react" ; import { Box, useHighlight } from "@chakra-ui/react" ; export default function HighlightExample2() { const hookHighlight = useHighlight({ text: `We will be using the useHighlight hook to highlight some words in this example.`, query: [ "useHighlight" , "highlight" , "example" ], }); return ( <Box display= "flex" justifyContent= "center" > {hookHighlight.map(({ match, text }) => { if (match === false ) return text; return ( <Box bgColor= "green" color= "white" padding= "0 2px" margin= "0 2px" > { " " } {text} </Box> ); })} </Box> ); } |
Output:
Chakra UI Typography Highlight
Chakra UI Typography Highlight Component is used to highlight any part of text. It is a perfect component to use if you want to attract user’s attention to any specific part of the text or if you want to highlight some import parts of a paragraph.
The text to highlight can be selected using the query prop of the Highlight Component while its styles prop is used to style the highlighted section of the text. If you want to highlight more than one substring then an array can also be passed to the query prop. Also the value passed to the query prop is case insensitive, i.e both w3wiki and w3wiki is same for it.
We will use the following approaches to implement Typography Highlight
Table of Content
- Approach 1: Without using the useHighlight hook:
- Approach 2: Using the useHighlight hook: