0

I'm new to react and struggling with how to transfer data from one component to another.

I referred some tutorials and blogs, but things aren't working for me.

I have two child components, Body-content.jsx and Profile.jsx and 1 parent component parent.jsx

I want to transfer some data from Body-content.jsx toProfile.jsx.

Here's my code

Body-content.jsx


class BodyContent extends React.Component {
    componentDidMount() {
        this.getUserList()
    }
    getUserList(){
      fetch('https://jsonplaceholder.typicode.com/users')
        .then(result => {
            return result.json();
        }).then(data =>{
           this.setState({
             users : data
           })
        })
    }

      render() {
        const user = this.state.users.map((userData, i) => (          
          <CardBody>
              ...some code here
              <Button color='primary' onClick={e => this.viewProfile(userData)}>View Profile</Button>
          </CardBody>
        </Card>
        ));
          return (
            <>
       <div>{user}</div>
            </>
          )
      }

      viewProfile = function (data) {
      }
  }
  export default BodyContent;

profile.jsx

class Profile extends React.Component {
  componentDidMount() {
  }
  render() {

    return (
      <>
        <TopNav />
        <main className="profile-page" ref="main">
                    <section>
                       //code goes here
                    </section>
        </main>
      </>
    );
  }
}

export default Profile;
Shashank
  • 437
  • 2
  • 6
  • 21

5 Answers5

1

Store your data in parent component and send it as props to children. If you have to change it in one of them, then send (also as prop) the function, which will change data in parent component.

Code sample:

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {someData: ''};
  } 

  changeData(newData) {
    this.setState({
      someData: newData
    });
  }

  render() {
    return (
      <>
        <Child1 setData={this.changeData} data={this.state.someData} />
        <Child2 setData={this.changeData} data={this.state.someData} />
      </>
    )
  }
}

Both of them will be able to change data in parent component using this.props.setData('newData')

wwilkowski
  • 341
  • 4
  • 14
0

If you want to share your state across the child component then you may need to move that property in parent's state which you may able to share between two child components.

  • Sibling to Sibling
    • Parent Component
  • Any to Any
    • Observer Pattern
    • Global Variables
    • Context

How to make a shared state between two react components?

Yash Bathia
  • 43
  • 1
  • 13
0

You can hoist state to parent component:

class Parent extends Component {
  state = {
    users
  };

  handleUsersChange = users => this.setState({ users });

  render() {
    const { users } = this.state;

    return (
      <React.Fragment>
        <Body-content onUsersChange={ this.handleUsersChange } />
        <Profile users={ users } />
      </React.Fragment>
    );
  }
}

...

class BodyContent extends React.Component {
    getUserList(){
      fetch('https://jsonplaceholder.typicode.com/users')
        .then(result => {
            return result.json();
        }).then(data =>{
           this.props.handleUsersChange(data);
        })
    }
  }
Andres
  • 967
  • 6
  • 7
0

In ReactJs the data flow is uni-directional - Top-to-bottom. The parents passes the data to respective children.

Here, since you want to share the data between two siblings. The data should be first available to their parent.

In order to do so, your getUserList api call should be inside of your parent, i.e your parent.jsx component.

From there you can pass the data as props to both the siblings.

Let me know if you need and further explanation to this. If needed, please share your parent.jsx code. I can help you further.

nitte93
  • 1,820
  • 3
  • 26
  • 42
0

Hi and welcome to the world of React,

If you want to share data between siblings components, you should always keep in mind that you should store your data at the highest common component (doc).

In your case that would mean having a parent component that holds your users list and the current profile in its state, and then render accordingly your list and the current profile.

A little example to get you on the "right track" sandbox:

class Parent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      users: [],
      currentIndex: null
    }
  } 

  componentDidMount() {
      this.getUserList()
  }

  getUserList(){
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(result => result.json())
      .then(data => {
         this.setState(() => ({
           users : data
         }))
      });
    }

  updateCurrent = (index) => {
    this.setState(() => ({ currentIndex: index }));
  } 

  render() {
    return (
      <div>
        <UserList 
          users={this.state.users}
          updateCurrent={this.updateCurrent}
        />

        {this.state.currentIndex !== null && (
          <Profile user={this.state.users[this.state.currentIndex]} />
         )}
      </div>
    )
  }
}

const UserList = (props) => (
  <div>
    {props.users.map((user, i) => (          
      <div key={user.id}>
         <button color='primary' onClick={() => props.updateCurrent(i)}>View Profile</button>
      </div>
    ))}
  </div>
);

const Profile = ({ user }) => (
  <div className="profile-page">
    {user.name}     
  </div>
);

Feel free to ask clarification if needed.

Happy coding,

P.E. Joëssel
  • 1,393
  • 10
  • 18