简体   繁体   中英

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,
  };
}

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.

You should pass mapStateToProps as the first parameter of connect (in your component).

Also, you never wire up your dispatch method toggleDiv to anything, so technically nothing would ever make your div visible. You could briefly test by updating your reducer such that the default state is { hidden: false } , and then go about wiring it up to be triggered by some kind of event somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM