I am trying to use ref on a search input in my Header component which ISN'T a higher order component to my ResultsList component. I want to set focus on the Header's search input from the ResultsList component. It is intuitive from the Header because all I have to do is the below. What if I wanted to create a button in ResultsList which would focus on the input element in Header? How do I pass this ref? I have read about forwardRef but I am not passing my ref forwards. ResultsList is not a child of Header.
import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
const Header = () => {
const searchInput = useRef(null);
const history = useHistory();
const [searchValue, setSearchValue] = useState(keyword);
function handleChange(event) {
setSearchValue(event.target.value);
}
function handleSearch(event) {
event.preventDefault();
if(searchValue) {
history.push(`/search/${searchValue}`);
} else {
searchInput.current.focus();
}
}
return (
<form onSubmit={handleSearch} role="search">
<input
value={searchValue}
onChange={handleChange}
className="HeaderSearch__input"
id="header-search-input"
placeholder="Search a repository"
ref={searchInput}>
</input>
</form>
);
}
export default Header;
My App component looks like this
import React from 'react';
import Header from './Header';
import ResultsList from './ResultsList';
function App() {
return (
<>
<Header />
<ResultsList />
</>
);
}
export default App;
forwardRef
: reactjs.org/docs/forwarding-refs.html – BranhamForwardRef
will also work but you'd need to pass it to both components - see demo here. I'd prefer using Context but both is OK. – Forehand