0

I am having two independent components in react and I want to call a method in first component that returns Some value to another component.

import React from 'react';
export default class A extend React{
    constructor(props){
     super(props);
    }

    getName = () =>{
       var name = "MyName";
       return name;
    }
    render(){
      //Some code to render
    }
}

Now In component B in want to call method getName() so that it returns name,which i want to use in component B.

import React from 'react';
export default class B extends React{
    constructor(props){
     super(props);
    }
    getName = () =>{
      //Want to call the getName method of component A here
    }

    render(){
      //Some code to render
    }

}
2
  • Do you use redux or context inside your project? maybe you can pass it via it? Commented Dec 29, 2019 at 13:30
  • how do you render these two components? Commented Dec 29, 2019 at 13:50

1 Answer 1

1

Use React lifting State Up.

Here is the official documentation.

Lifting State Up

Sign up to request clarification or add additional context in comments.

6 Comments

but we don't know how OP is rendering these compoents.
You can keep the value in the parent component's state and pass it to both child components. Then you can keep a function to update the value of that particular state variable in parent and pass it down to component A so when when you update the value in component a it will call the fucntion which is passed down as prop from parent component to component A which will update the value in parent component. and will get reflected in both the child. I will add a sample code, which I guess will work for you.
Please copy it to a text editor import React, {Component, Fragment} from 'react'; import A from './A'; import B from './B'; export default class Parent extend Component{ state = { data: 0, } updateData = (data) => { this.setState({data}); } render () { const {data} = this.state; return ( <Fragment> <A data={data} updateData={this.updateData} /> <B data={data} /> </Fragment> ); } }
Please copy it to a text editor Component A import React, {Component} from 'react'; export default class A extend Component{ updateData = () => { const {data, updateData} = this.props; updateData(data); } render () { const {data} = this.state; return ( <div onClick={this.updateData}>{data}</div> ); } }
Please copy it to a text editor Component B import React, {Component} from 'react'; export default class B extend Component{ render () { const {data} = this.state; return ( <div>{data}</div> ); } }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.