pass ref from parent 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: react pass prop to parent
import React, { useState, Component } from 'react';
import Input from '../../shared/input-box/InputBox'
const Form = function (props) {
const [value, setValue] = useState('');
const onchange = (data) => {
setValue(data)
console.log("Form>", data);
}
return (
<div>
<Input data={value} onchange={(e) => { onchange(e) }}/>
</div>
);
}
export default Form;
import React from 'react';
const Input = function (props) {
console.log("Props in Input :", props);
const handleChange = event => {
props.onchange(event.target.value);
}
return (
<div>
<input placeholder="name"
id="name"
onChange= {handleChange}
/>
</div>
);
}
export default Input;
Example 3: pass element from child to parent react
Parent:
<div className="col-sm-9">
<SelectLanguage onSelectLanguage={this.handleLanguage} />
</div>
Child:
handleLangChange = () => {
var lang = this.dropdown.value;
this.props.onSelectLanguage(lang);
}
Example 4: use ref call parent component to child react
const { forwardRef, useRef, useImperativeHandle } = React;
const Child = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
getAlert() {
alert("getAlert from Child");
}
}));
return <h1>Hi</h1>;
});
const Parent = () => {
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.getAlert()}>Click</button>
</div>
);
};
ReactDOM.render(
<Parent />,
document.getElementById('root')
);