Reputation: 59
I have Component named Home
which contains LeftNav
, BookSearch
and HomeCart
Component. BookSearch
Component has a input field and HomeCart
component has a button. When the button in HomeCart
component clicked, I need to focus the input field in BookSearch
Component.
I researched a bit and I could able to only focus an element from the same Component only. How can I achieve the desired behaviour this using React Ref?
Home.jsx
class Home extends React.Component {
render() {
return (
<React.Fragment>
<div className="row no-gutters app">
<div className="col-sm-12 col-md-12 col-lg-2">
<LeftNav />
</div>
<div className="col-sm-12 col-md-12 col-lg-7 books-panel">
<BookSearch test={this.test}/>
</div>
<div className="col-sm-12 col-md-12 col-lg-3 cart-panel">
<HomeCart onClick={thi} />
</div>
</div>
</React.Fragment>
);
}
}
BookSearch.jsx
class BookSearch extends React.Component {
render() {
return (
<React.Fragment>
<button onClick={this.test}>Focus</button>
<div className="row text-center">
<div className="col-12">
<form onSubmit={this.handleSubmit}>
<h2 className="mt-5">Start searching your favorite books</h2>
<label htmlFor="search-query" className="sr-only">
Search by book name
</label>
<input
name="search-query"
onChange={this.handleChange}
type="search"
className="book-search"
value={this.state.query}
placeholder="Start searching...."
/>
<button type="submit" className="btn btn-primary btn-lg">
Search
</button>
</form>
</div>
</div>
</React.Fragment>
);
}
}
HomeCart.jsx
class HomeCart extends React.Component {
focusSearchBookInput(){
this.props.focusSearchBookInput()
}
render() {
const { cart_items } = this.props;
const cartTable = ();
const noCartItems = (
<React.Fragment>
<p>No items currently available in your cart. </p>
<button onClick={this.focusSearchBookInput} className="btn btn-success mt-5">
<ion-icon name="search" /> Start Searching
</button>
</React.Fragment>
);
return (
<React.Fragment>
<div className="row text-center">
<div className="col-12">
<h2 className="mt-5 mb-5">Books in your cart</h2>
{cart_items.length > 0 ? cartTable : noCartItems}
</div>
</div>
</React.Fragment>
);
}
}
Upvotes: 3
Views: 3253
Reputation: 3316
One solution could be...
Create the ref and a click handler that sets focus on the ref in Home.jsx
class Home extends React.Component {
inputRef = React.createRef();
focusHandler = () => {
this.inputRef.current.focus();
}
render() {
return (
<React.Fragment>
<div className="row no-gutters app">
<div className="col-sm-12 col-md-12 col-lg-2">
<LeftNav />
</div>
<div className="col-sm-12 col-md-12 col-lg-7 books-panel">
<BookSearch inputRef={this.inputRef} />
</div>
<div className="col-sm-12 col-md-12 col-lg-3 cart-panel">
<HomeCart focusHandler={this.focusHandler} />
</div>
</div>
</React.Fragment>
);
}
}
Add ref={this.props.inputRef}
to the input in BookSearch.jsx
Add onClick={this.props.focusHandler}
to the button in HomeCart.jsx
Upvotes: 3