How to pass data to another file

#1

I have this react component

import React, {Component} from 'react';
import axios from 'axios';

export default class apidata extends Component {
    state = {
      items: []
    }
  
    componentDidMount() {
      axios.get(`https://url`)
        .then(res => {
          const items = res.data;
          this.setState({ items });
        })
    }
}

how to pass Items data to another file ?

#2

Assuming by “another file” you mean a child component, then you can pass it as props.

When the Ajax request completes and state gets updated, the props in the child component will update, too.

#3

Thanks I want to pass the data to parent copponent

#4

Ok, then you could create a function on the parent element that handles the response/data from the child and pass that function as a prop. Then call that function from the child.

Alternatively, you might have a look at the context API, which provides a way to share values between components without having to pass a prop through every level of the tree.

As a side note, it is often a good idea to do the fetching of data in the parent component and then keep your child components as dumb as possible, just passing them the data they need to display.

1 Like
#5

Thanks alot