📱테스트 환경
"react": "18.2.0"
"react-dom": "18.2.0"
"typescript": "^4.9.5"
검색기능이 있으면 당연 하이라이트 기능도 있는게 이쁘고 사용자 입장에서도 좋다고 생각한다.
// Search.tsx
const [keyword, setKeyword] = useState<string>("");
<Search
placeholder="input search text"
onSearch={onSearch}
enterButton
onChange={(e) => {
setText(e.target.value);
}}
/>
<Title>
{Highlighting({ text: data.title, keyword: keyword })}
</Title>
useState 를 통해서 검색어 키워드를 가지고 있고 이 키워드가 하이라이팅 글자가 될 것이다.
// type.tsx
export interface HighlightingData {
text: string;
keyword: string;
}
// Highlighting.tsx
const Highlighting = ({ text, keyword }: HighlightingData) => {
const parts = text.split(new RegExp(`(${keyword})`, "gi"));
return (
<span>
{parts.map((part, index) =>
part.toLowerCase() === keyword.toLowerCase() ? (
<Highlight key={index}>{part}</Highlight>
) : (
part
)
)}
</span>
);
};
export default Highlighting;
// StyledHighlighting.tsx
export const Highlight = styled.span`
display: inline;
box-shadow: inset 0 -14px 0 #f7cecc;
&:after {
content: "";
width: 0;
height: 50%;
display: inline-block;
background: #f7cecc;
}
`;
변수로는 전체 텍스트와, 키워드 값을 받기위해서 Type 을 만들어주고
split 를 이용해 키워드와 나머지 텍스트로 잘라주면 준비는 끝난다.
여기서 대소문자 구분없이 찾아내기 위해 gi 를 사용
map 함수를 통해 parts 가 반복되면서 keyword 와 같은 경우 highlight 를 적용
box-shadow 의 -14px 이 높이다. 낮을수록 높아지고 커질수록 높이가 낮아진다.
결과는 다음과같이 키워드가 2로 들어왔을 때 해당 텍스트에 하이라이팅 효과가 적용되는 걸 볼 수 있다.
'Javascript > React' 카테고리의 다른 글
[React] Html Tag 걸러내는 방법 (1) | 2024.04.18 |
---|---|
[React] 공백문자 추가   (0) | 2024.04.15 |
[React] "@babel/plugin-proposal-private-property-in-object" ... (0) | 2024.04.12 |
[React] console.log 두번 출력될때 React.StrictMode (0) | 2024.04.11 |
[React] 이미지 클릭 시 파일 선택 <Input /> 사용하기 (0) | 2024.04.09 |