Simon Breton Simon Breton - 3 months ago 10
React JSX Question

How should I pass data in my render method with React/redux

I'm trying to adapt the following react bar chart to my react/redux project : http://codepen.io/clindsey/collab/RRZBQm/. Most of the code is ok for me however I don't really understand the rendering part :

setTimeout(() => {
const data = {'alpha': 82, 'bravo': 20, 'charlie': 68};
const size = [480, 320];
const margins = [40, 40, 40, 40];
ReactDOM.render(
<BarChart {...{data, margins, size}} />
, document.getElementById('js-app'));
}, 0);


Why in this example, "const" are passed in ReactDOM.render function through the BarChart element ?

When adapting this to my local project I've got the following code in my container :

const App = () => (

<div>
<Component1 />
<Component2 />
<BarChart />
</div>
);

export default App;


then I use
mapStateToProps
function to pass
const data
,
const size
and
const margins
, like this :

const data = {'alpha': 82, 'bravo': 20, 'charlie': 68};
const size = [480, 320];
const margins = [40, 40, 40, 40];

function mapStateToProps(state) {
return {
data: data,
size: size,
margins: margins,
};
};


It's working fine but I didn't really understand what I'm doing. Not sure if It's good practice or it it's heaven make sense.

Thanks.

Answer

The whole idea of mapStateToProps is to link your Redux store to your (in your case) React Components. Typically you'd use it like this

function mapStateToProps(state){
    return {
        propertyOne: state.myPropertyOne, //state.myPropertyOne comes from your redux store, when you return this object, your component gets this object
        propertyTwo: state.myPropertyTwo
    };
}

You didn't have to pass your const variables into the function for it to work. If they were in that file you could have just used them directly.

Seems to work just fine https://jsfiddle.net/julianljk/qkjkqf6q/

Comments