How to toggle boolean state of react component?

前端 未结 9 1818
别跟我提以往
别跟我提以往 2021-01-29 23:45

I\'d like to know how to toggle a boolean state of a react component. For instance:

I have boolean state check in the constructor of my component:

const         


        
9条回答
  •  自闭症患者
    2021-01-30 00:39

    I was landed in this page when I am searching to use toggle state in React component using Redux but I don't find here any approach using the same.

    So, I think it might help someone who was struggling to implement toggle state using Redux.

    My reducer file goes here. I get the initial state false by default.

    const INITIAL_STATE = { popup: false };
    export default (state = INITIAL_STATE, action) => {
        switch (action.type) {
            case "POPUP":
                return {
                    ...state,
                    popup: action.value
                };
            default:
                return state;
        }
        return state;
    };
    

    I change state on clicking the image. So, my img tag goes here with onClick function.

    
    

    My Toggle Popup function goes below, which call Dispatcher.

    const togglePopup = ev => {
        ev.preventDefault();
        props.handlePopup(!props.popup);
    };
    

    This call goes to below mapDispatchToProps function which reflects back the toggled state.

    const mapDispatchToProps = dispatch => ({
        handlePopup: value => dispatch({ type: "POPUP", value })
    });
    

    Thank you.

提交回复
热议问题