1.0.1 • Published 7 years ago

react-redux-combine-components v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
7 years ago

React Redux Combine Components build status npm version

Combine Redux connected components the same way you combine Redux reducers.

Reducers only need to manage the section of the global state tree which is relevant to them, but react-redux connected components need to know where in the state tree their data is held.

With React Redux Combine Components you can assign components to different properties of the state tree the same way you do with reducers. This aids reusability, as components need to know nothing about global state, and improves performance as they are only rerendered on change to their substree, instead of the global state.

Installation

React Redux Combine Components requires React Redux 5 or later.

npm install --save react-redux-combine-components

This assumes that you’re using npm package manager with a module bundler like Webpack or Browserify to consume CommonJS modules.

Documentation

Example

// Reducer thinks state is just an array of todos
const todoReducer = (state = [], action) => {
    if (action === "ADD_TODO") {
        return [].concat(state, [new Todo()])
    }
};

// And now so does the component
const mapStateToTodosProps = (state) => ({ todos: state });

let Todos = (props) => <TodoList {...props} />;
Todos = connect(mapStateToTodosProps)(Todos);

// Reducer thinks state is just an array of appointments
const calendarReducer = (state = [], action) => {
    if (action === "ADD_APPOINTMENT") {
        return [].concat(state, [new Appointment()])
    }
};

// And now so does the component
const mapStateToCalendarProps = (state) => ({ appointments: state });

let Calendar = (props) => <CalendarPage {...props} />;
Calendar = connect(mapStateToCalendarProps)(Calendar);

// Make different reducers responsible for different parts of the state tree
const reducer = combineReducers({
    todos: todoReducer,
    calendar: calendarReducer
});

// And now pass different parts of the state tree to different components
({ Todos, Calendar } = combineConnected({
    todos: Todos,
    calendar: Calendar
}));

const store = createStore(reducer);

ReactDOM.render(
    <Provider store={ store }>
        <div>
            <Todos />
            <Calendar />
        </div>
    </Provider>,
    document.getElementById('root')
);

See a complete example demonstrating reusability here.

License

MIT