I'm working on a small search component that highlights text if it matches a word search (just for better understanding, I know there are libraries out there that do this.)
I can't seem to get my RegExp to trigger the i (case sensitive) parameter upon clicking a checkbox.
Attaching my code - built using create-react-app.
import React, { useState } from "react";
import './highlighter.css';
const Highlighter = (props) => {
const [value, setValue] = useState("");
const [searchValue, setSearchValue] = useState("");
const [checked, setChecked] = useState(false);
const [sensitive, setSensitive] = useState("i");
let highlight = null;
const handleChange = (event) => {
setValue(event.target.value);
};
console.log(value);
const handleSearchChange = (event) => {
setSearchValue(event.target.value);
};
console.log(searchValue);
const getHighlightedText = (value, searchValue) => {
let regex = new RegExp(`(${searchValue})`, `g${sensitive}`);
console.log(regex);
const parts = value.split(regex);
//console.log(parts);
highlight = <span> { parts.map((part, i) =>
<span key={i} style={part === searchValue ? { backgroundColor: 'Yellow' } : {} }>
{ part }
</span>)
} </span>;
}
const checkedTest = () => {
if(checked === true) {
setSensitive(" ") // makes it case sensitive
console.log(sensitive);
setChecked(true);
} else {
setSensitive("i")
console.log(sensitive);
setChecked(false);
}
}
return (
<>
<form className="text-search-form">
<textarea className="source-text" value={value} onChange={handleChange}/>
<input className="search-term" value={searchValue} onChange={handleSearchChange} onKeyPress={getHighlightedText(value, searchValue)} />
<label htmlFor="caseSensitive">case sensitive?
<input
type="checkbox"
className="case-sensitive"
name="caseSensitive"
defaultChecked={checked}
onClick={getHighlightedText(value, searchValue)}
onChange={checkedTest}
/>
</label>
</form>
<div className="result">{highlight}</div>
</>
);
};
export default Highlighter;
Expected result: When checkbox is NOT checked, regex expression searches the textarea and finds all copies of the searched word in the input. Upon clicking the checkbox, make the search case sensitive.
I'm newer to react, so if you see a better approach please let me know.
P.S. trying to use functional components
Aucun commentaire:
Enregistrer un commentaire