Answer the question
In order to leave comments, you need to log in
How to implement this React code in Redux using mapStateToProps and mapDispatchToProps?
Hello! I just started learning Redux and I want to learn how to write code using Redux but I need help from more experienced developers. There are examples of applications on the Internet, but they are too heavy for a beginner, you need something simpler, for a start, I think you can try to implement some simple functionality. The first thing that came to mind was tabs. In addition, I want to see how mapStateToProps and mapDispatchToProps are used in practice.
I have a React code that implements tabs:
import React from "react";
import ReactDOM from "react-dom";
const items = [
{ title: "London", content: "London is the capital city of England." },
{ title: "Paris", content: "Paris is the capital of France." },
{ title: "Tokyo", content: "Tokyo is the capital of Japan." }
];
class TabContent extends React.Component {
render() {
return (
<div className="tabcontent">
<h3>{this.props.title}</h3>
<p>{this.props.content}</p>
</div>
);
}
}
class Tabs extends React.Component {
state = {
active: 0
};
openTab = e => {
this.setState({
active: +e.target.dataset.index
});
};
render() {
return (
<div>
<div className="tab">
{this.props.items.map((n, i) => (
<button
className={`tablinks ${i === this.state.active ? "active" : ""}`}
onClick={this.openTab}
data-index={i}
>
{n.title}
</button>
))}
</div>
{this.props.items[this.state.active] && (
<TabContent {...this.props.items[this.state.active]} />
)}
</div>
);
}
}
ReactDOM.render(<Tabs items={items} />, document.getElementById("root"));
Answer the question
In order to leave comments, you need to log in
1) install redux, react-redux in the project
2) add HOC connect and connect mapStateToProps and mapDispatchToProps:
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { Provider, connect } from "react-redux";
// здесь описание вышеприведенных компонентов ...
// для трансформации текущего redux-store в props компонента
const mapStateToProps = state => {
return {
items: state.items
}
}
// для трансформации текущих redux-dispatch в props компонента
const mapDispatchToProps = dispatch => {
return {
addItem: {title, content} => {
dispatch(addItem({title, content}));
},
// ...
}
}
const TabsWithRedux = connect(mapStateToProps, mapDispatchToProps)(Tabs);
// -----------
// redux-store
// -----------
// начальный state
const initialState = {
items: [
{ title: "London", content: "London is the capital city of England." },
{ title: "Paris", content: "Paris is the capital of France." },
{ title: "Tokyo", content: "Tokyo is the capital of Japan." }
]
};
// создадим, к примеру, функционал добавления нового item
const ADD_ITEM = "ADD_ITEM";
// экшн
const addItem = item => {
return {
type: ADD_ITEM,
payload: item
};
};
// рутовый редьюсер
const rootReducer = (state = initialState, {type, payload} => {
switch (type) {
case ADD_ITEM:
return {
items: [...state.items, payload]
}
default:
return state
}
});
// основной стор
const store = createStore(rootReducer);
// рендер
ReactDOM.render(
<Provider store={store}>
<TabsWithRedux items={items} />
</Provider>,
document.getElementById("root")
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question