0

I am new to react & need some help. I am getting data from a REST API using Axios. I have two Components. A Parent & Child Component. In parent Component I am fetching the Summarised data from API having multiple records while the Child component is used to make another API call for Details of the record when user clicks on a specific record in the Parent Component. The Parent Component has 3 attribute ( Document-Number, document-Type & Approver ). I need to pass the "Doc-Number" & " Doc-Type" values to the child Component API URl when user clicks on the button.

Note: I donot have any dedicated ID attribute in the Parent API response and that's the reason I am using index as a key.

Here is My Parent Component

import React, { Component } from "react";
import axios from "axios";
import Getdetails from "./Getdetails";
class Parent extends Component {
constructor(props) {
    super(props);
    this.state = {
      records: [],
      errorMessage: "",
    };
  }

  componentDidMount() {
    axios
      .get( "http://www.example.Api.com/generalInfo&limit=10&offset=2" )
      .then((res) => {
        this.setState({ records: res.data });
        console.log(res);
      })
  }

render() {
    const { records } = this.state;
    return (
        <div>
          <ul>
            {records.map((record, index) => (
              <li key={index}>
                Document Number : {record.Number}
                Document Type: {record.documentType}
                Approver : {record.approver} 
                //I Want to send the "document Number & documentType" to Childdetails component Url when user click on this button. 
                <button onClick={{record.Number} & {record.documentType}}>Get Details</button> 
              </li>
            ))}
          </ul>
        </div>
      )
}
}
export default Parent;

Here is My Child Component

import React, { Component } from "react";
import axios from "axios";
import Parent from "Parent";

class ChildDetails extends Component {

    constructor(props) {
        super(props);
    
        this.state = {
          getdetails: [],
          errorMessage: "",
        };
      }

      componentDidMount() {
        axios
          .get("http://www.example-Details-API.com/documentType={record.documentType}/id={record.Number}")
          .then((res) => {
            this.setState({ getdetails: res.data });
            console.log(res);
          })
      }

    render() {
        const { getdetails } = this.state;
        return (
            <div>
                <h1>Get Details</h1>
                <ul>
                  <li> Number : {getdetails.Number} </li>
                  <li> Title : {getdetails.Title} </li>
                  <li> Submit Date : {getdetails.Date} </li>
                  <li> Site : {getdetails.site} </li>
                 <li> Requester : {getdetails.requesterName}</li>
                 <li> document Type : {getdetails.documentType}</li>
              </ul>

            </div>
        )
    }
}

export default ChildDetails

Thanks To everyone and Your help is really appreciated.

3
  • You have to pass that data as props to your child component, and of course, add in render of the parent the child component to use. Something like <ChildComponent documentType={record.documentType} documentNumber={record.documentNumber} > Commented Oct 16, 2020 at 5:28
  • Hi @pmiranda . Thanks for your reply. I donot have a stable Id attribute in the response from the API & that's the reason I am using the index. How could I refer that specific record to child component. Could you please show me a snipped of the code from the above section? Thanks Commented Oct 16, 2020 at 5:37
  • So, any of the answers are the correct one for you? Commented Oct 16, 2020 at 16:28

4 Answers 4

1

When you talk about Parent and Child components I expect to see the Child rendered by the Parent, I am not sure if this is your case. Anyway, the main way to pass data from parents to childs are via the props. Applied to your example:

In the parent's render function:

<ChildDetails record={record} />

In the child's render function:

componentDidMount() {
    axios
      .get(`http://www.example-Details-API.com/documentType=${props.record.documentType}/id=${props.record.Number}`)
      .then((res) => {
        this.setState({ getdetails: res.data });
        console.log(res);
      })
  }

See that in the child the data is accessed via props.record.

If your ChildDetails is not rendered by the Parent, then you need to pass the information to upper levels through callbacks.

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

Comments

0

Passing data as a prop to child component

  const onClickHandler = (record,document)  => {
     return (
      <ChildDetails recordNumber={record} documentType={document}/>
      )
    };
    

Passing data as parameters to event handler

    <button onClick={onClickHanlder(record.Number,record.documentType)}>Get Details</button>

If you wannna use index you can use it as a third argument

Comments

0

You can add two more state values in your parent component such as:

this.state = {
      records: [],
      errorMessage: "",
      Selected-Doc-Number: ""
      Selected-Doc-Type: ""
    };

Now on you can set these state values (Selected-Doc-Number, Selected-Doc-Type) on the click of record button on parent component as:

const selectRecordForChildComponent = (selectedDocNumber, selectedDocType) => {
      this.setState({Selected-Doc-Number: selectedDocNumber, 
                     Selected-Doc-Type: selectedDocType})
}

<button 
onClick={() => {selectRecordForChildComponent(record.Number, record.documentType)}}>
Get Details
</button> 

Now on you can pass these values (Selected-Doc-Number, Selected-Doc-Type) to child component using props as from the Parent-component:

<ChildDetails 
selectDocNumber = {this.state.Selected-Doc-Number} 
selectedDocType = {this.state.Selected-Doc-Type} />

Now you can access these passed props in <ChildDetails> component using it's props as for example:

componentDidMount() {
        const docNumber = this.props.selectDocNumber 
        const docType = this.props.selectedDocType 
        axios
          .get(`http://www.example-Details-API.com/documentType=${docType}/id=${docNumber}`)
          .then((res) => {
            this.setState({ getdetails: res.data });
            console.log(res);
          })
      }

Hope this may help...

1 Comment

Thanks alot @Abhay Kumar for you time & efforts
0

In the parent component onClick create a function that will be called and return the props to the child component.

<button onClick={() => this.handleClick(record.number, record.documentType)}>Get Details</button>

And the handle click function should be like that

handleClick(num, type) {
   return (
      <Child recordNum={num} docType={type}></Child>
   )
};

Don't forget to bind the function in the constructor. You can then call the external API in the did mount function in the child and replace the url with the required props from parent like in the above example this.props.recordNum and this.props.docType.

2 Comments

Hi @Mohd Zeefan . How to bind the function in the constructor please?
this.handleClick = this.handleClick.bind(this); @Raza

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.