zac
zac

Reputation: 4898

How to pass data to another file?

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

export default class apidata extends Component {

    componentDidMount() {
      axios.get(`https://url`)
        .then(res => {
          const items = res.data;

        })
    }
}

How to pass the items json data to parent class file that import this class ?

Upvotes: 0

Views: 44

Answers (1)

The Qodesmith
The Qodesmith

Reputation: 3375

You can have a method live on the parent that expects the items and does something with it. Then, pass it down to the ApiData component as props. Here's an example:

class Parent extends Component {
  handleItems(items) {
    // Do something
  }

  render() {
    return <ApiData handleItems={this.handleItems} />;
  }
}

class ApiData extends Component {
  componentDidMount() {
    axios.get(`https://url`)
      .then(res => {
        const items = res.data;
        this.props.handleItems(items);
      })
  }
}

Upvotes: 1

Related Questions