0

I have an onClick function that changes a className's state so show and hide some stylings that I have. The button works fine on the first click, but can't be clicked again after that.

Shown below I have my component that connects to my redux store. I created the handleClick function to call the actionCreator that I have show in my actions. I want the onClick function to fire on each click and change click that is in my state to the opposite of what it was previously. Am I missing using previous state somewhere? Am I directly changing my state when I should be copying state? Anyways, hopefully the question makes sense.

Edit: I have found that when I click the button the click state is staying true, don't know why it isn't switching.

class BackDrop extends React.Component {

    handleClick = () => {
        this.props.projectClick();
    };
    render() {
        console.log(this.props);
    return (
        <div className={this.props.click ? 'backdrop-click' : 'backdrop'}>
            <button className="btn-click" onClick={()=> {this.handleClick()}}>
                {this.props.click ? 'Back' : 'View Projects'}
            </button>
            <ProjectDisplay
                click={this.props.click}
            />
        </div>
        )
    }
}
const mapStatetoProps = (state) => {
    return state;
};


export default connect(mapStatetoProps, actionCreators)(BackDrop);
//Reducer

const initialState = {
    click: false,
};

const mainReducer = (state = initialState, action) => {
    switch(action.type) {
        case "PROJECT_CLICK":
            return {
                ...state,
                click: !action.click,
            };
        default:
            return {
                ...state,
            }
    }
};

export default mainReducer;

//Action

export function projectClick(click) {
    return {
        type: "PROJECT_CLICK",
        click,
    }
}
Nate Watts
  • 351
  • 1
  • 3
  • 6
  • You don't show the declaration of `actionCreators` in your snippets. However, when you call `this.props.projectClick();` you don't pass an argument there – can that be your issue? On another note, if it is always a toggle you can also use `click: !state.click` in your reducer. Happy debugging. ;-) – sthzg Nov 23 '17 at 21:37
  • That was the problem. Ugh. I was using props not state. – Nate Watts Nov 23 '17 at 21:41

1 Answers1

0

Turns out I had used click: !action.click when I should've done click: !state.click

Nate Watts
  • 351
  • 1
  • 3
  • 6