passing parent ref to child props in react code example
Example 1: 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 2: 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 3: how to pass props from child to parent
class ToDoList extends React.Component { constructor(props) { super(props); this.state = { listDataFromChild: null }; }, myCallback = (dataFromChild) => { this.setState({ listDataFromChild: dataFromChild }); }, otherFn = () => { [...within this other function now I still have access to this.state.listDataFromChild...] } render() { return ( <div> <ToDoItem callbackFromParent={this.myCallback}/> [...now here I can pass this.state.listDataFromChild as a prop to any other child component...] </div> ); }});
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')
);