Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140734

Where to make a toggle action in this react redux code?

$
0
0

I have 2 files here: App.js and reducer.js I try to use React & Redux for creating onclick toggle action (ex: background color change). Can anyone help me to where can I make toggle action in this code? (I made setTimeout action in mapDispatchToProps before and it worked but toggle action not.) see the code:

App.js

import React, { Component } from "react";
import "./App.css";
import { connect } from "react-redux";

class App extends Component {
  render() {
    return (
      <div>
        <button
          style={{
            backgroundColor: this.props.backgroundColor
          }}
        >
          hello
        </button>
        <button onClick={this.props.changeTheColor}>change</button>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    backgroundColor: state.backgroundColor
  };
};

const mapDispatchToProps = dispatch => {
  return {
    changeTheColor: () => {
      dispatch({ type: "CHANGE_COLOR" }); //I think something should change here but I have no idea how :(
    }
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(App);


and reducer.js

const initialState = {
  backgroundColor: "red"
};

const reducer = (state = initialState, action) => {
  const updatedState = { ...state };

  if (action.type === "CHANGE_COLOR") {
    updatedState.backgroundColor = "yellow";  // I added else/if operation there before and didn't worked :(
  }

  return updatedState;
};

export default reducer;

does someone has any idea(s) how to make toggle action there? I want to change button red background color to yellow and toggle back the acton


Viewing all articles
Browse latest Browse all 140734

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>