0

I'm new to react I need to pass array to another component via props but i got an issue

in Component1

this.state={
   data:[], //some values inside both it
   col:[]
    }

<Component2 data={[...this.state.data]} col={[...this.state.col]}/>

in Component2

constructor(props){
    super(props)

    this.state = {
        data:[...this.props.data],
        col:[...this.props.col],

    }
    console.log(this.state.data+' inside state')
}

when I console.log i get the below output

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] inside state

one of my array has 17 elements but why am not getting the actual data?is there any syntax error in my code?

1
  • one of my array has 17 elements but why am not getting the actual data? What do you mean, your question shows it logs the data. Maybe try: console.log(this.state.data,' inside state')`. I'm also not sure why you want copy data that is passed to Component2 to local state and why you make a shallow copy of the data twice. Commented May 5, 2020 at 12:51

3 Answers 3

2

In both of your components, you should not have to use the extract/destructuring syntax. Instead just assign the values as they are.

Example:

Component 1

this.state={
   data:[], //some values inside both it
   col:[]
}

<Component2 data={this.state.data} col={this.state.col}/>

Component 2

constructor(props){
    super(props)

    this.state = {
        data: this.props.data,
        col: this.props.col,

    }
    // Also you were casting to a string here, just pass the data as second parameter to log it.
    console.log('inside state', this.state.data)
}
Sign up to request clarification or add additional context in comments.

Comments

1
com 1:

     <Component2 data={this.state.data} col={this.state.col} />

com 2: 

    constructor(props){
        super(props)

        this.state = {
            data:this.props.data,
            col:this.props.col,

        }
        console.log(this.state.data + ' inside state');
        console.log(this.state.col + ' inside state');
    }

Comments

0

React documentation explicitly states of not setting state from props, instead use the props directly. That is what they are for.

Comments

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.