First, we need to create a file for our store at src/shared/redux/configureStore.js:
- Let's go ahead and write the following code:
// Dependencies
import { createStore } from 'redux';
// Root Reducer
import rootReducer from '../reducers';
export default function configureStore(initialState) {
return createStore(
rootReducer,
initialState
);
}
File: src/shared/redux/configureStore.js
- The second thing we need to do is to create our initialState variable in our public/index.html file. For now, we will create a device state to detect whether the user is using a mobile or a desktop:
<body>
<div id="root"></div>
<script>
// Detecting the user device
const isMobile = /iPhone|Android/i.test(navigator.userAgent);
// Creating our initialState
const initialState = {
device: {
isMobile
}
};
// Saving our initialState to the window object
window.initialState = initialState;
</script>
</body>
File: public/index.html
- We need to create a reducers directory in our shared folder. The first reducer we need to create is deviceReducer:
export default function deviceReducer(state = {}) {
return state;
}
File: src/shared/reducers/deviceReducer.js
- Once we have created deviceReducer, we need to create an index.js file, where we are going to import all our reducers and combine them into a rootReducer:
// Dependencies
import { combineReducers } from 'redux';
// Shared Reducers
import device from './deviceReducer';
const rootReducer = combineReducers({
device
});
export default rootReducer;
File: src/shared/reducers/index.js
- Now let's modify our src/index.js file. We need to create our Redux Store and pass it to our provider:
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import './index.css';
// Redux Store
import configureStore from './shared/redux/configureStore';
// Routes
import AppRoutes from './routes';
// Configuring Redux Store
const store = configureStore(window.initialState);
// DOM
const rootElement = document.getElementById('root');
// App Wrapper
const renderApp = Component => {
render(
<Provider store={store}>
<Router>
<Component />
</Router>
</Provider>,
rootElement
);
};
// Rendering our App
renderApp(AppRoutes);
- Now we can edit our Home component. We need to connect our component to Redux using connect from react-redux, and then, using mapStateToProps, we are going to retrieve the device's state:
import React from 'react';
import { bool } from 'prop-types';
import { connect } from 'react-redux';
const Home = props => {
const { isMobile } = props;
return (
<div className="Home">
<h1>Home</h1>
<p>
You are using:
<strong>{isMobile ? 'mobile' : 'desktop'}</strong>
</p>
</div>
);
};
Home.propTypes = {
isMobile: bool
};
function mapStateToProps(state) {
return {
isMobile: state.device.isMobile
};
}
function mapDispatchToProps() {
return {};
}
export default connect(mapStateToProps, mapDispatchToProps)(Home);