Please tell me how to replace document.addEventListener with react components
const searchIsActive = createRef()
const searchContainer = createRef()
document.addEventListener('focusin', () => {
searchContainer.current.style.background = "#303130";
}
)
return(
<div ref={ searchContainer } className="search__container">
<img src="img"></img>
<input ref={ searchIsActive } type="text"></input>
</div>
)
CodePudding user response:
You can do it with two handlers onFocus and onBlur with a single ref
to your input wrapper:
function App() {
const searchContainer = React.createRef();
const onFocusHandler = () => {
searchContainer.current.style.background = "#303130";
};
const onBlurHandler = () => {
searchContainer.current.style.background = "#FFFFFF";
};
return (
<div ref={searchContainer} className="search__container">
<img src="img"></img>
<input
type="text"
onFocus={onFocusHandler}
onBlur={onBlurHandler}
></input>
</div>
);
}
ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>