0
votes

I want to send props from my parent component to child component. this is the way i have used In parent component state-->

chartArray:[
        {
            id:0,
            chart:'LineChart',
            device:1,
            sensor:1,

        },
        {
            id:1,
            chart:'LineChart',
            device:2,
            sensor:4,
        },]

In parent component render method --> I user Chart component and send those props

                            {
                            chartArray.map((obj,index)=>{

                                return(
                                    <Grid item xs={12} md={12} key={index}
                                    className={classes.mainGrid} 
                                    style={{paddingBottom:30}}
                                     >


                                    <div>
                                        <div  >
                                            <div>
                                            <Typography
                                            variant={"h5"}
                                            >
                                                Device Id: {obj.device}

                                                <IconButton style={{float:'right'}}
                                                onClick={this.handleDeleteChart.bind(this,index)}
                                                >
                                                    <DeleteIcon fontSize="small" />
                                                </IconButton>
                                            </Typography>
                                            </div>

                                        </div>

                                        <div>
                                        <Typography variant={"subtitle1"}>
                                            Sensor: Temperature
                                        </Typography>

                                        </div>
                                    </div>


                                        <Paper elevation={3} 
                                        style={{
                                            overflowX: 'scroll',

                                        }}
                                        >
                                            **<Chart
                                            chartType={obj.chart} 
                                            sensorId={obj.sensor}
                                            deviceId={obj.device}
                                            />**

                                        </Paper>
                                    </Grid>

                                )



                            }

                        )}

In child component-->

export default class Chart extends Component {

constructor(props){
    super(props);

    this.state={
        id:0,
        chart:props.chartType,
        device:props.deviceId,
        sensor:props.sensorId,
    }
}

async componentDidMount(){

    const response2 = await fetch(`/api/SensorData/${this.state.device}/${this.state.sensor}`)
    const bodySensors = await response2.json()

    const labels1=[]
    const data1=[]

    bodySensors.map((chartdata)=>{
        return(
            labels1.push(chartdata.date),
            data1.push(chartdata.value)
        )

    })

    this.setState({

        dataLineChart:{
            labels:[...labels1],
            datasets:[
                {
                fill:false,
                label:'Temperature',
                data:[...data1],
                backgroundColor:'rgba(210, 77, 87, 1)',
                borderColor:'rgba(137, 196, 244, 1)',
                pointBorderWidth:1,
                pointHoverRadius:10,
                pointHoverBackgroundColor:'rgba(210, 77, 87, 1)',
                pointHoverBorderColor:'rgba(137, 196, 244, 1)',
                pointHoverBorderWidth:2,
                pointRadius:2,
                // how much closer to pop up point
                pointHitRadius:10

                // steppedLine:true
            }
        ]

        }

    })


}



render() { 
    const{chartType}=this.props
    const {dataLineChart} = this.state        

    if (chartType==='BarChart')
        return (
            <BarChart />
        )
    else if (chartType==='LineChart')
        return (
            <LineChart ccData={dataLineChart}/>
        )
    else if (chartType==='PieChart')
        return (
            <PieChart/>
        )
}

}

when i use this way to use those props outside render function. It works. When I add objects to parent component state--> chartArray it also works. But when ever i delete something from that chartArray it does not send props to child component? I'm really confused here. please help. Thank you

2

2 Answers

0
votes

Please follow this example.

Parent Component

import React, {Component, useEffect, useState} from 'react';
import PChild from "./PChild";

export class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {items: []};
    }

    componentDidMount() {
        let json = [];
        json.push({track: { id:1, name: 'Black Sabbath, from the album Black Sabbath (1970)'}});
        json.push({track: { id:2, name: 'Blackfield, from the album Blackfield (2004)'}});
        json.push({track: { id:3, name: 'Bo Diddley, from the album Bo Diddley (1958)'}});
        json.push({track: { id:4, name: 'Damn Yankees, from the album Damn Yankees (1990)'}});
        this.setState({items: json});
    }

    render() {
        return (
            <div>
                <PChild items={this.state.items} name="Khabir"/>
            </div>
        );
    }
}

Child Component

import React, {useEffect, useState} from 'react';

// Parent to Child communication
export class PChild extends React.Component {

    componentDidUpdate() {
        console.log(this.props.items);
        console.log(this.props.name);
    }

    render() {
        return (
            <div>
                {this.props.items.map((item, i) => {
                    return <li key={item.track.id}>
                        {(`Item ${i+1} - ${item.track.name}`)}
                    </li>
                })}
            </div>
        );
    }
}
0
votes

Because the Child doesn't get re-rendered every time the Parent Props change what you need to change is in the Child Component instead of componentDidMount use componentDidUpdate. Inside it you have to check with simple if statement the passed props value. Something in the sense:

    componentDidUpdate(prevProps) {
    if(prevProps.chartType !== this.props.chartType||prevProps.sensorId !== 
    this.props.sensorId||prevProps.deviceId !== this.props.deviceId) { ...... your code}

}

Of course, that is assuming everything else is working smoothly.