Zhao Yi Zhao Yi -4 years ago 161
React JSX Question

Try to understand this javascript source code

I am reading a react code as below:

const AppWithNavigationState = connect(state => ({
nav: state.nav,
}))(({dispatch, nav}) => (
<Root navigation={addNavigationHelpers({ dispatch, state: nav })}/>
));


I don't quite understand the above code. Especially this line
<Root navigation={addNavigationHelpers({ dispatch, state: nav })}/>
.

Is above code equal to below code?

class AppWithNavigation extends Component{

render(){
return (<Root navigation={this.props.addNavigationHelpers.bind(this)}/>);
}

}
const mapStateToProps = (state) => {
return {
nav: state.nav,
}
}

const mapDispatchToProps = (dispatch) => {
return {
addNavigationHelpers: (nav)=>{
dispatch(addNavigationHelpers(nav))
}

}
}

const AppWithNavigationState = connect(mapStateToProps, mapDispatchToProps)(AppWithNavigation);

Answer Source
<Root navigation={addNavigationHelpers({ dispatch, state: nav })}/>

This is JSX code. It is a component called Root that takes one prop navigation. The value of the navigation is the returned value of a function call to addNavigationHelpers. The addNavigationHelpers function call has an object as argument: { dispatch, state: nav }. This object can also be written like this:

{ dispatch: dispatch, state: nav }

Which might be more readable.

You also ask if the code below is equal to the one above. It is not. I will focus on comparing the two Root components:

<Root navigation={this.props.addNavigationHelpers.bind(this)}/>

This component takes the addNavigationHelpers function as prop to the component. It will not call the addNavigationHelpers function and send the returned value, but it will send the function itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download