ReactJS: Trigger event from child in parent component - reactjs

i have two components: 1.Parent 2.Child
there is an event in child component called onChange() which return a value.
i want to receive the value which was returned from OnChange() in componentDidMount() in parent component.
Example:
class Parent extends PureComponent {
componentDidMount() {
let value = CHILD.onChange(); //triggered when ever onChange()
}
render(){
return(
<Child />
)
}
}
const Child = () => {
const onChange = () => {
const value = 1
return value;
};
}

class Parent extends PureComponent {
handleChildChange = value => {
//Do your stuff with value, pass it to the state and take it from there if you like
}
render(){
return(
<Child handleChange={this.handleChildChange} />
)
}
}
const Child = (props) => {
const onChange = () => {
value = 1
props.handleChange(value);
}
};
}

Related

How to passing refs to component in React

I have a data like this:
constructor(props) {
this.a = React.createRef();
this.b = React.createRef();
this.c = React.createRef();
}
setValue = (data = {}) => {
const {a='', b='', c=''} = data.constructor === ({}).constructor ? data : {};
this.a.current.setValue(a, data => {
this.b.current.setValue(data.b, data => {
this.c.current.setValue(data.c);
}
}
}
}
How could I passing that to my customized Component like this:
<CusComponent ref={this.a}>
Here is the function to get value in CusComponent:
value = function (a,b,c) {
if (arguments.length) {
if (a) {
this.setState({a}, () => {
this.value_a.value(a);
if (b) {
this.setState({b}, () => {
this.value_b.value(b);
if (c) {
this.setState({c}, () => {
this.value_c.value(c);
}
}
})
}
}
}
Thanks a lot!
Yes you can pass a ref down to a child component with:
<CusComponent ref={this.a}>
Make sure you create CusComponent with React.forwardRef because that creates an argument ref alongside props. This `ref you can directly bind to anything in your child component.
const CusComponent = React.forwardRef((props, ref) => (
<button ref={ref}>
{props.children}
</button>
));
You can read more in detail about this in the documentation.
If however both your parent and child component are class components then pass down the ref to CusComponent like so:
<CusComponent childref={this.a}>
Name the property something other than ref. Then you can access this ref in child component like below eg.
export default class CusComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div ref={this.props.childref}>Here</div>;
}
}

How can I pass a prop from child to parent component

How can I pass a prop (when modified) from Child Component to a Parent Component.
Some Details :
I am working on an existing codebase where I have Parent Component embedded in
'unstated.Container' and a separate Child Component , where I am trying to add a button. When
a user clicks this button some value gets updated , which needs to be passed to the Parent
component .
Thank you.
import {Container} from 'unstated';
class DelContainer extends Container{
state = { sortAsc : true, notified : null}
setVal = async (Id, value) => { console.log (`Id : ${Id}); console.log('value: ${value}); }
}
//Child Component (Separate file)
const ChildItems = (props) => {
const [some_value ] = props;
const [some_color, setColor] = useState(" ");
const MarkIt = ({some_value})
{
some_value = this.props.some_value; //ISSUE HERE
}
return (
<IconButton >
<StarOutlinedIcon onClick = {MarkIt} style={{color: `${some_color}`}}/>
</IconButton>
);
}
//Parent Component (Separate file)
import {Subscribe} from 'unstated';
const DelList = (props) => {
return(
<Subscribe to ={[DelContainer]}>
{
(delStore) => {
const[person, isLoading] = delStore.state;
return(
<div>
<List className = {props.className} isLoading = {Loading}>
{
isLoading && person
.map((person, index)=>{
return <ChildItem key={index}
person = {person}
some_value = {delStore.MarkIt(some_value)};
}
}
</List<
</div>
)
}
}
);
}
Read this :
How to update parent's state in React?
Reactjs DOCS:
https://reactjs.org/docs/lifting-state-up.html
class Parent extends React.Component {
liftStateHander=()=> {
this.setState({
name:"John"
})
}
render() {
return <Child handler={this.liftStateHander} />
}
}
class Child extends React.Component {
render() {
return (
<button onClick={this.props.handler}>
Click For Change State Parent
</button>
)
}
}

Passing data from child component to parent getting error prop.onCall not a function

I am calling a parent function from functional child component
but I am getting error props.onCall is not a function.
Also props come as undefined when I do console.log(props)
Here is the parent function :
class Parent {
construtor(props) {
super(props);
this.myFun = this.myFun.bind(this);
}
myFun = val = {
console.log(val);
}
render{
return (
<Child onCall={this.myFun} />
)
}
}
Here is the child function :
const Child = props => {
Handlefn = () => {
props.onCall("hi");
}
}
You have a ton of typos in your app.
Try this
Parent:
import React from "react";
import Child from "./Child";
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.myFun = this.myFun.bind(this);
}
myFun = val => {
console.log(val);
};
render() {
return <Child onCall={this.myFun} />;
}
}
Child:
import React from "react";
const Child = props => {
const Handlefn = () => {
props.onCall("hi");
};
return <h1 onClick={Handlefn}>Hi</h1>;
};
export default Child;

React passed data from child to parent not logging in parent

I tried to pass data from a child component to it's parent but it isn't showing in the parent component.
In parent component I want to display the duration of a service that is selected in the child component.
In the child component I can log the selected service but it isn't passing to its parent:
Parent component:
class CalenderModal extends React.Component {
state={selectedService:[]}
// handover of child data to parent
handleServiceSelect = (selectedServiceObj) => {
this.setState({selectedService: selectedServiceObj});
console.log('inside CalendarModal:', this.state.selectedService)
}
handleRemove = () => {
this.props.onRemove();
}
handleSave = () => {
const fullname = this.fullname.value;
const phone = this.phone.value;
this.props.onSave({
fullname,
phone,
});
}
render() {
return (
<div className="customModal">
<div>Choose service you want to schedule:</div>
/// child component
<ServiceSearch onServiceSelect={()=> this.handleServiceSelect}/>
<div>{this.state.selectedService.duration} hours</div>
<button className="customModal__button customModal__button_example" onClick={this.handleSave}>{action}</button>
</div>
);
}
}
export default CalenderModal;
Child component:
class ServiceList extends Component {
constructor(props) {
super(props);
}
servicesToRender=[]
handleServiceSelect = (event) => {
var selectedServiceId = event.target.value;
var selectedService = this.servicesToRender.find(({id})=> id === selectedServiceId )
console.log("inside Service search:",selectedService)
this.props.onServiceSelect(selectedService);
}
render() {
const FEED_QUERY = gql`
{
servicefeed {
id
name
cost
duration
}
}
`
return (
<Query query={FEED_QUERY} >
{({ loading, error, data }) => {
if (loading) return <div>Fetching</div>
if (error) return <div>Error</div>
this.servicesToRender= data.servicefeed
// const servicesToRender = data.servicefeed
return (
<React.Fragment>
<label class="my-1 mr-2" for="inlineFormCustomSelectPref">choose service:</label>
<select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref" onChange={this.handleServiceSelect}>
{this.servicesToRender.map(service => <ServiceSearchOption key={service.id} service={service} />)}
</select>
</React.Fragment>
)
}}
</Query>
)
}
}
export default ServiceList
I'm not sure what I'm missing here.
You haven't called the function in parent when passing it as props and using arrow function inline. The correct ways is below
<ServiceSearch onServiceSelect={()=> this.handleServiceSelect()}/>
However, you could have simply passed the function reference without an arrow function since the handleServiceSelect is already and arrow function and will have function binding
<ServiceSearch onServiceSelect={this.handleServiceSelect}/>

React Native Pass Parent Method to Child Component

I am trying to pass method from my parent component to child component. My code is correct i think but still it shows the error undefined is not an object(evaluating '_this2.props.updateData') . I don't know whats the issue because i searched the internet a lot and everyone is passing props to child like this. Kindly tell what am i missing
Parent:
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={val => this.updateData(val)} />
);
}
Child:
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick()}>Test</button>
);
}
}
`class Child extends React.Component {
handleClick = () => {
const passedData = 'child data'
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}`
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
}
render() {
return (
<Child updateData={this.updateData} />
);
}
}
and child component: `
class Child extends React.Component {
const passedData = 'child data'
handleClick = () => {
this.props.updateData(passedData);
}
render() {
return (
<button onClick={this.handleClick}>Test</button>
);
}
}
`
You need to pass the function directly, not as a callback
class Parent extends React.Component {
updateData = (data) => {
console.log(`This data isn't parent data. It's ${data}.`)
// data should be 'child data' when the
// Test button in the child component is clicked
}
render() {
return (
<Child updateData={this.updateData} />
);
}
I think you need to pass a function like this. Check out this solution.

Resources