Last active
October 13, 2020 17:13
-
-
Save jbarrow/b53cb21106f16235004effac34d42c1a to your computer and use it in GitHub Desktop.
A React component that captures the browser ctrl+f.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
class Searchable extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
'text': 'This is some text.', | |
'highlighted': 'This is some text.' | |
}; | |
this.captureSearch = this.captureSearch.bind(this); | |
} | |
searchText(query) { | |
if (query.length == 0) return []; | |
var startIndex = 0, index, indices = [], reconstituted = ""; | |
const doc = this.state.text.toLowerCase(); | |
while ((index = doc.indexOf(query.toLowerCase(), startIndex)) > -1) { | |
reconstituted += this.state.text.slice(startIndex, index); | |
reconstituted += "<b>"; | |
reconstituted += this.state.text.slice(index, index+query.length); | |
reconstituted += "</b>"; | |
startIndex = index + query.length; | |
} | |
reconstituted += this.state.text.slice(startIndex); | |
this.setState({ 'highlighted': reconstituted }) | |
} | |
captureSearch(e) { | |
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) { | |
e.preventDefault(); | |
this.searchBar.focus(); | |
} | |
} | |
componentDidMount() { | |
window.addEventListener("keydown", this.captureSearch); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('keydown', this.captureSearch); | |
} | |
render() { | |
return ( | |
<div> | |
<input type="text" | |
ref={(input) => { this.searchBar = input; }} | |
onChange={(e) => this.searchText(e.target.value)} /><br /><br /> | |
<div className="text" dangerouslySetInnerHTML={{ | |
__html: this.state.highlighted | |
}}> | |
</div> | |
</div> | |
); | |
} | |
} | |
function App() { | |
return ( | |
<div className="App"> | |
<Searchable /> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment