passing ref to child react code example
Example 1: react forwardref
const FancyButton = React.forwardRef((props, ref) => (
<button ref={ref} className="FancyButton">
{props.children}
</button>
));
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
Example 2: refs react js
class Lesson9Refs extends Component {
onAddProduct = () => {
alert(this.refs.productname.value);
}
return (
<div>
<div className="container">
<div class="card mt-10">
<div class="card-header">
Featured
</div>
<div class="card-body">
<label> Product Name: </label>
<input type='text' className="form-control" ref="productname" />
<button type="submit" className="btn btn-primary" onClick={ this.onAddProduct } >
Add Product
</button>
</div>
</div>
<div className="row mt-10">
{ elements }
</div>
</div>
</div>
);
}
}
export default Lesson9Refs;