Redux in React JS
Redux is a state management library that is often used with React. Here's an example of how to use Redux in a React application:
```jsx
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
// Action types
const ADD_TODO = 'ADD_TODO';
const TOGGLE_TODO = 'TOGGLE_TODO';
// Action creators
function addTodo(text) {
return { type: ADD_TODO, text };
}
function toggleTodo(index) {
return { type: TOGGLE_TODO, index };
}
// Reducer
function todos(state = [], action) {
switch (action.type) {
case ADD_TODO:
return [...state, { text: action.text, completed: false }];
case TOGGLE_TODO:
return state.map((todo, index) => {
if (index === action.index) {
return { ...todo, completed: !todo.completed };
}
return todo;
});
default:
return state;
}
}
// Store
const store = createStore(todos);
// Component
function TodoList(props) {
return (
<ul>
{props.todos.map((todo, index) => (
<li key={index} onClick={() => props.toggle(index)} style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
{todo.text}
</li>
))}
</ul>
);
}
// Connect the component to the Redux store
const ConnectedTodoList = connect(
state => ({ todos: state }),
dispatch => ({
add: text => dispatch(addTodo(text)),
toggle: index => dispatch(toggleTodo(index))
})
)(TodoList);
// Render the component with the Redux store provider
ReactDOM.render(
<Provider store={store}>
<ConnectedTodoList />
</Provider>,
document.getElementById('root')
);
In this example, the createStore function from the redux library is used to create a Redux store. The Provider component from the react-redux library is used to provide the store to the application.
The connect function from the react-redux library is used to connect the TodoList component to the Redux store. The TodoList component receives the todos prop from the store and the add and toggle functions to dispatch actions to the store.
The addTodo and toggleTodo functions are action creators that create actions to be dispatched to the store. The todos function is a reducer that updates the state of the store based on the actions dispatched to it.
No comments:
Post a Comment