chefcurry7 chefcurry7 - 1 month ago 18
React JSX Question

React clone children & attach props not working

I have this piece of code

render() {
const { schools, currentSchool, claims } = this.state;
let loggedIn = this.state.loggedIn ? true : false;
let user = this.state.user;

var children = React.Children.map(this.props.children, function (child) {
return React.cloneElement(child, {
**claims: this.state.claims**
})
})
return (
<div>
<HeaderContainer
user={user}
claims={claims}
onLogin={this.onLoginButtonClick} />

{ loggedIn && <NavContainer claims={claims}/> }

{children}

<Footer/>
</div>
)
}
}


however I don't have access to
this.state.claims
for some reason as "this" is undefined . Why is that and how can I resolve this?

Answer

There are 2 ways you can achieve this one is in render function use that = this let that = this; and then in the function instead of this.state.claims use:

return React.cloneElement(child, {//use that variable here } )

or the other way you can achieve this is by using arrow function

var children = this.props.children.map(child => { return React.cloneElement(child, { **claims: this.state.claims** })

javascript is all about scope and variables in javascript are function scoped not block scoped. Read more about scope in javascript.