evaldschukin
evaldschukin

Reputation: 29

How i can realize switch logic with Redux

I apologize for such a newbie question, but how I can realize switching between tabs using react-redux. How to reproduce this logic using the storage My inital code: App.js

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { tab: 0 };
  }

  switchingTabs = (event, value) => {
    this.setState({
      tab: value,
    });
  };

  render() {
    return (
      <div className="App">
        <Container>
          <AppBar className="bar" position="static">
            <Tabs value={this.state.tab} onChange={this.switchingTabs}>
              <Tab label="Commits Info"></Tab>
              <Tab label="User info"></Tab>
            </Tabs>
          </AppBar>
          <TabBackbone value={this.state.tab} index={0}></TabBackbone>
          <TabBackbone value={this.state.tab} index={1}></TabBackbone>
          <Content></Content>
        </Container>
      </div>
    );
  }

Index.js

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

ReactDOM.render(<App />, document.getElementById("root"));

I tried to do it myself, but I don't know how to export value to reducer

Upvotes: 0

Views: 25

Answers (1)

lmonninger
lmonninger

Reputation: 961

It sounds like you're just getting started with Redux, which is great!

  1. You need a state that will represent your tab selection:
    export interface IState {
        tabNumber : number
    }

    export initialState : IState = {
        tabNumber : 0
    }
  1. You are going to need to define a reducer:
    export function appReducer(state=initialState, action : AnyAction) : IState{
    // state reduction logic here
    }

  1. Then create a store:
    export const store = createStore(appReducer); // import {createStore} from "redux";
  1. Then wrap your application or portion thereof in a Provider that takes your store:
   <Provider store={store}> {/* import {Provider} from "react-redux"; */}
        <App/>
   </Provider>

That said, I would consider whether you need Redux. I typically use the React Context API, especially in situations like this where the context is intended to essentially perform the function of a higher-order function.

Upvotes: 1

Related Questions