0

I've created a React class with state variable as array type.

export default class Demo extends React.Component {
  constructor(props){
    super(props)
    this.state ={
      test: []
    }
  }

Now, when I use console.log(this.state.test) in render function then it returns object type. I thought it is for the unique-key purpose when mapping.

But, what if I just want to define an array for push method?

Is there any other way to define the same? Please guide.

1
  • Have you tried pushing to it? It's definitely an array, but it's a key : value object. The objects property value is an array. test is not an array, it's just a key Commented Jul 8, 2017 at 1:43

1 Answer 1

2

Remember that array are objects in javascipt.

typeof([]) //outputs object

To print the array in readable form, you can use JSON.stringify

console.log(JSON.stringify(this.state.test, null, 2))

To set array in the state, you can use the setState method:

this.setState({test: [/* new array */]})

In react I really like to use the pre tag to show state while I'm developing.

Add this to render:

<pre>{JSON.stringify(this.state, null, 2)}</pre>
Sign up to request clarification or add additional context in comments.

1 Comment

typeof is an operator, not a function, so the parens around [] are superfluous.

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.