Answer the question
In order to leave comments, you need to log in
What mistakes did I make when writing Redux code? What do I need to change in my code?
I have implemented very simple tabs in React.js.
You can see how it works in the sandbox:
https://codesandbox.io/s/react-tabs-redux-example-36psr
And I'll write the code here:
import React from "react";
import ReactDOM from "react-dom";
const items = [{content:"London"}, {content:"Paris"}];
class Content extends React.Component {
render(){
return (
<div>
{this.props.content}
</div>
);
}
}
class Tabs extends React.Component {
state = {
active: 0
}
open = (e) => {
this.setState({active: +e.target.dataset.index})
}
render(){
return(
<div>
{this.props.items.map((n, i)=>
<button data-index={i} onClick={this.open}>{n.content}</button>
)}
{this.props.items[this.state.active] && <Content {...this.props.items[this.state.active]} />}
</div>
);
}
}
ReactDOM.render(<Tabs items={items} />, document.getElementById("root"));
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import {createStore} from "redux";
import { combineReducers } from "redux";
import { connect } from "react-redux";
// action
function changeTab (change){
return{
type: "CHANGE_TAB",
change: change
};
}
//Reducer
function reducer(state={someTab:{active: 0}},action){
switch(action.type){
case "CHANGE_TAB":
return Object.assign({}, state, {
change: action.change
});
default:
return state;
}
}
// CombineReducer
const allReducers = combineReducers({
oneReducer: reducer
});
// Tabs - main component
const items = [{content:"London"},{content:"Paris"}];
class Tabs extends React.Component {
render(){
return(
<div>
{this.props.items.map((n,i)=>
<button data-index={i} onClick={e => this.props.changeTab({this.props.someTab.active:+e.target.dataset.index})}>{n.content}</button>
)}
this.props.items[this.props.someTab.active] && <Content {...this.props.items[this.props.someTab.active]} />}
</div>
);
function mapStateToProps(state){
return {
onOneReducer: state.oneReducer
};
}
function matchDispatchToProps (dispatch) {
return {
changeTab: () => dispatch(changeTab),
};
}
connect(mapStateToProps,matchDispatchToProps)(Tabs);
}
}
// Content - other component
class Content extends React.Component {
render(){
return (
<div>
{this.props.content}
</div>
);
}
}
// index.js
const store = createStore(allReducers);
ReactDOM.render(
<Provider>
<Tabs items={items} />
</Provider>,
document.getElementById("root")
);
Answer the question
In order to leave comments, you need to log in
1. messed up with quotes
2. didn’t pass the store to the provider
3. some kind of fierce game with the logic of the store and switching
4. Wrapped an unfinished component in the provider
Karoch, something like this should happen https://codesandbox.io/s/ react-tabs-redux-example-63186
I have implemented very simple tabs in React.js.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question