JLegendre JLegendre - 4 months ago 247
Javascript Question

Show/Hide div with CSS in React JS/Redux

I am attempting to toggle a div using CSS and

className
s. I am using redux to update the state of the boolean. I can confirm through the redux chrome extension that the state is changing but the div does not show up. If anyone has any ideas as to what is wrong, please let me know.

Component:

const ShowHideDiv = (props) => (
<div>
<Button onClick={props.toggleDiv} />
<div className={props.hidden ? style.hidden : style.open}>
<TextInput />
</div>
</div>
);

function mapDispatchToProps(dispatch) {
return {
toggleDiv: () => dispatch(toggleDiv()),
};
}

export default connect(null, mapDispatchToProps)(ShowHideDiv);


actions.js:

const toggleDiv = () => {
return {
type: 'TOGGLE_DIV',
};
};


reducers.js

const toggleDivReducer = (state = { hidden: true}, action) => {
switch(action.type) {
case 'TOGGLE_DIV':
return Object.assign({}, state, {hidden: !state.hidden});
default:
return state;
}
};


style.scss

.hidden {
display: none;
}

.open {
display: inline;
}


Display page

<ShowHideDiv hidden={props.hidden} />

function mapStateToProps({demo}) {
return {
hidden: demo.hidden,
};
}

Answer

I have figured out what I was doing wrong. The issue was in my display page mapStateToProps. I was not assigning the hidden prop correctly.

Instead of doing this:

function mapStateToProps({demo}) {
  return {
    hidden: demo.hidden,
  };
}

I should have been doing this:

function mapStateToProps({demo}) {
  return {
    hidden: demo.toggleDivReducer.hidden,
  };
}

Make sure to keep this in mind especially if you have a combineReducers function.