Marcus Vain Marcus Vain - 2 months ago 19
React JSX Question

How to get event from components to container in React Redux

I'm new to Redux.
I handled the basic Facebook Flux architecture very easily and made some nice app with it.
But I struggle very hard to get very simple Redux App to work.
My main concern is about containers and the way they catch events from components.

I have this very simple App :

CONTAINER

import { connect } from 'react-redux'
import {changevalue} from 'actions'
import App from 'components/App'


const mapStateToProps = (state) => {
return {
selector:state.value
}
}

const mapDispatchToProps = (dispatch) => {
return {
onClick: (e) => {
console.log(e)
dispatch(changeValue())
}
}
}

const AppContainer = connect(
mapStateToProps,
mapDispatchToProps
)(App)

export default AppContainer;


Component

import React, {Component} from 'react'
import Selector from 'components/Selector'
import Displayer from 'components/Displayer'


const App = (selector, onClick) => (
<div>
<Selector onClick={(e) => onClick}/>
<Displayer />
</div>
)

export default App;


CHILD COMPONENT

import React, {Component} from 'react'


const Selector = ({onClick}) => (
<div onClick={onClick}>click me</div>
)

export default Selector;


onClick event does not reach the container's mapDispatchToProps.
I feel that if I get this work, I get a revelation, and finally get the Redux thing! ;)

Can anybody help me get this, please ? (The Redux doc is TOTALLY NOT helpfull...)

Answer

The problem is in the App component. In the onClick property of the Selector component, you're passing a function which returns the definition of a function, not the result.

const App = (selector, onClick) => (
  <div>
    <Selector onClick={(e) => onClick}/> // here is the problem
    <Displayer />
  </div>
)

You should simply do this instead:

const App = (selector, onClick) => (
  <div>
    <Selector onClick={(e) => onClick(e)}/>
    <Displayer />
  </div>
)

Or even simpler:

const App = (selector, onClick) => (
  <div>
    <Selector onClick={onClick}/>
    <Displayer />
  </div>
)
Comments