0

I have an Array that I get from Props: this.arrayContenido = this.props.children;. If I console.log this, i have an array like this: https://puu.sh/Dlsce.png

ok, I need split this array for animate them with gsap. I mapped this array, and assign each element of this array to new array(this.children =[] in constructor):

{this.arrayContenido.map(function(item, i) {
                return (
                  <div key={i}  ref={div => (this.childrens[i] = div)}>
                    {item}
                  </div>
                );
              })}

Why when i do console.log in componentDidMount for this.childrens i have undefined results?

3
  • Typo? Your code says this.childrens[i] The plural of "child" is "children", you have "childrens" Commented Apr 29, 2019 at 10:26
  • i dont understand what u say :( Commented Apr 29, 2019 at 10:28
  • In the code you use this.childrens but in the explanation you wrote this.children. Note the s Commented Apr 29, 2019 at 10:29

2 Answers 2

1

Looks like you have problems with this. You can use arrow function to get proper this

{
  this.arrayContenido.map((item, i) => {
    return (
      <div key={i} ref={div => (this.childrens[i] = div)}>
        {item}
      </div>
    );
  });
}

This is assuming that this code lies in the render function or any function with the correct this, which is the component.

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

Comments

0

The first issue is the anonymous function without binding, this won't be what you expect inside it and therefore this.children will be undefined. You can use an arrow function instead which provides the auto binding:

{this.arrayContenido.map((item, i) => {
    return (
        <div key={i}  ref={div => (this.childrens[i] = div)}>
            {item}
        </div>
    );
})}

You were already using arrow function in the ref prop, but not in the surrounding anonymous function...

The second issue is with this.props.children: it shouldn't be seen as an array. If you want to iterate over a React component's children you have to use React.Children.map(this.props.children, () => ....)

look into React.Children for more details.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.