0

My Component has a Property defined as array but i cant iterate the values by numeric keys. It seems that the keys are of type string. Am I missing something?

class Test extends React.Component {
    render () {
        let parse = [];
            for (let i in Object.keys(this.props.test)) {
                parse.push(
                    <div key={i}>
                        {i} {typeof i} {this.props.test[i]}
                    </div>
                )
    }
    return (
        <div> 
            {parse}
        </div>
    )
    }
}

Test.propTypes = {
    test: React.PropTypes.array
}

ReactDOM.render(
   <Test test={["a", "b", "c"]} />, 
   document.getElementById('main') 
);

Shows that the keys of Property Test are strings.

Codepen Example

7
  • 1
    Because keys of an JavaScript object are always strings Commented Apr 18, 2017 at 10:33
  • 1
    Even if you write {1: 'foo'}, the 1 will become a string Commented Apr 18, 2017 at 10:33
  • But i defined the Property as ["a", "b", "c"]. And it has PropTypes set to array also. Commented Apr 18, 2017 at 10:36
  • 1
    See the docs of Object.keys here: developer.mozilla.org/docs/Web/JavaScript/Reference/… Commented Apr 18, 2017 at 10:37
  • 1
    Object.keys() returns an array whose elements are strings Commented Apr 18, 2017 at 10:37

2 Answers 2

1

In your case, if you want to iterate with numerical keys, just use map, forEach or a classic for i < length loop, here is the map example:

this.props.test.map((el, i) => (
  <div key={i}>
    {i} {typeof i} {el}
  </div>
))

Using non-numerical keys are totally fine. Moreover, sometimes using indexes as keys is not a good idea.

For example if your array may change sorting or delete/insert elements at the beginning or the middle, React may do many unnecessary operations (unmout/re-mount them)

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

Comments

1

You can better organise your code calling map function on your array,

class Test extends React.Component {
  render () {
    const {test} = this.props;

    return (
       <div>
         {test.map((t, i) =>
            <div key = {i}>{i} {typeof i} {t}</div>
         )}
       </div>
    );
   }
}

Test.propTypes = {
  test: React.PropTypes.array
};

ReactDOM.render(
    <Test test={["a", "b", "c"]} />, 
    document.getElementById('main')
);

1 Comment

Object.keys is not required here, its already an array of strings, you can directly use map on this.props.test :)

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.