<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dang Thanh Tam on Medium]]></title>
        <description><![CDATA[Stories by Dang Thanh Tam on Medium]]></description>
        <link>https://medium.com/@dangthanhtam?source=rss-46f5d611191e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sk0fDyQe7HIyucyZ.</url>
            <title>Stories by Dang Thanh Tam on Medium</title>
            <link>https://medium.com/@dangthanhtam?source=rss-46f5d611191e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 08:23:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dangthanhtam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to set up a project with react, redux, babel, and webpack, hot-reload from scratch]]></title>
            <link>https://medium.com/@dangthanhtam/how-to-set-up-a-project-with-react-redux-babel-and-webpack-hot-reload-from-scratch-b81f258ccbe1?source=rss-46f5d611191e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b81f258ccbe1</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[babeljs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Dang Thanh Tam]]></dc:creator>
            <pubDate>Tue, 20 Mar 2018 22:33:00 GMT</pubDate>
            <atom:updated>2018-03-20T22:57:04.626Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*rtzK5sNif6xRfHGZ410Xgw.jpeg" /></figure><p>There are plenty of boilerplate codes to start a project quickly then why do we need to build a project from scratch? Well, if we want something fast, then yeah, it would be wise to start a project from there. If we however want to learn, to control every piece of our code base, to include in our project only things that we want/need, then we should start a project from scratch.</p><p>At the end of this tutorial, we will have a simple project that has:</p><ul><li>three react components: Root, Controller, and Displayer;</li><li>redux as centralized state for the whole app;</li><li>react-redux to map redux’s state to components;</li><li>babel to help us write the latest version of javascript/ES;</li><li>webpack-hot-reload to speed up development: we save a file and then we can see the change almost instantly;</li><li>and finally webpack configurations for development and production.</li></ul><p>The tutorial is done in macOS. In Windows, there might be a slightly difference in CLI commands but the steps/ideas remain the same.</p><p>The tutorial assumes that we have already had node/npm installed on our Mac.</p><p>Let’s start by creating a folder named my_react_boilerplate and then switch to that folder!</p><pre>mkdir my_react_boilerplate<br>cd my_react_boilerplate</pre><h3>Step 0: React without any dependencies</h3><p>We can use React without the need of installing anything. We just need to add two external scripts into a target HTML: React, and ReactDOM . It is however advisable in React website that we should not use it in production environment. In case you are curious to see how it looks then let’s give it a try otherwise you can go to <strong>step 1</strong></p><p>Let’s create an index.html file with the content below</p><pre>touch index.html</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b227572c55f31a013efc7de841d646b/href">https://medium.com/media/4b227572c55f31a013efc7de841d646b/href</a></iframe><p>Let’s install a lite http-server to quickly check the result. I personally prefer using <em>http-server </em>tool. So, here we go with the option to install it globally. We need to execute the command in sudo permission since the installation will require the write access to system folders</p><pre>sudo npm install -g http-server</pre><p>Ok, cool — now let’s start the http-server</p><pre>http-server</pre><p>If everything go well we will see “Hello React!” when access to localhost:8080</p><h3>Step 1: Set up React and Webpack</h3><p>Init a package.json file</p><pre>npm init</pre><p>Let’s press enter to skip all the questions for now. After finishing it, we can see a package.json in the folder.</p><p>Let’s add two more dependencies: react and react-dom</p><pre>npm install --save react react-dom</pre><p>In practice, to build a Single-Page Application, we need to organize our source into many modules. This is why a tool like Webpack is needed to help us pack all the modules and their dependencies into one bundle which is then be included easily into a HTML file. Let’s add Webpack to our project’s dependencies and because we only need it for development hence — save-dev is needed. We also need Webpack cli (Command Line Interface) to work in terminal.</p><pre>npm install --save-dev webpack webpack-cli</pre><p>Next is to move the javascript out of HTML file to make it as an independent js file. We will host all js files into an <em>app </em>folder. So let’s go first by creating a folder named <em>app</em> and then create a js file called <em>index.js</em> inside the <em>app</em> folder.</p><pre>mkdir app<br>touch ./app/index.js</pre><p>Enter the following code for the <em>index.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23ba3b77e68035804b2afabe72182e58/href">https://medium.com/media/23ba3b77e68035804b2afabe72182e58/href</a></iframe><p>Now, let’s set up a configuration file for Webpack, it is recommended way by Webpack team.</p><pre>touch webpack.config.js</pre><p>Enter the following code for the webpack.config.js. We just need to configure two things for now: input js file and output bundle</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b284e8e11fe03e7ee3653697706e2fab/href">https://medium.com/media/b284e8e11fe03e7ee3653697706e2fab/href</a></iframe><p>Now, let’s use webpack cli to package the source</p><pre>webpack</pre><p>Webpack will use the default configuration file (<em>webpack.config.js</em>) if we don’t specify it by using <em>— config</em> parameter. After running the command above, there will be a warning from Webpack telling us that no mode is defined. We will fix it in later steps of this tutorial.</p><p>Now, if you check the project folder, there will be a file named <em>bundle.js</em> located inside a folder named <em>dist. </em>It’s created by Webpack. The next step is to modify file <em>index.html</em> in order to include the js file which has just been created by Webpack. If we follow step 0, then we will remove the external scripts to react and react-dom js either.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6836a160c85dca1203723518df222e0a/href">https://medium.com/media/6836a160c85dca1203723518df222e0a/href</a></iframe><p>If we start the http-server now, we can see “Hello React!”.</p><p>Ok, so wepack and react, react dom is set up. Let’s move to the next step</p><h3>Step 2: Adding Babel to support JSX</h3><p>Defining a React component by using <em>React.createElement</em> is verbose and is not really convenient for us to build complex React component. Hence, the need of JSX. Fundamentally, JSX just provides syntactic sugar for the <em>React.createElement(component, props, ...children)</em> function.</p><p>To support JSX, we will need a javascript pre-compiler to compile all jsx into <em>React.createElement</em>. In the context of this tutorial we will use Babel. Let’s install babel-preset-react, a preset of Babel that could compile JSX</p><pre>npm install --save-dev babel-preset-react</pre><p>Next is to add a Babel config file</p><pre>touch .babelrc</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3b05d8dbdc62f8ee7ad2c675fc36126/href">https://medium.com/media/b3b05d8dbdc62f8ee7ad2c675fc36126/href</a></iframe><p>Let’s modify file <em>index.js</em> to use JSX</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/104c02110e4388c524190591102e944f/href">https://medium.com/media/104c02110e4388c524190591102e944f/href</a></iframe><p>Now, if we build the app again using <em>webpack </em>command in terminal, we will get the message below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*rFJpa1iibVGaI5NxNH1Hqw.png" /></figure><p>It is because Webpack is using its default Loader which does not support JSX syntax. Let’s install <em>babel-loader</em> and then update the webpack config file in order to tell webpack to use that new babel loader.</p><pre>npm install --save-dev babel-loader</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/187be301fa308c17cc568c08988a74b2/href">https://medium.com/media/187be301fa308c17cc568c08988a74b2/href</a></iframe><p>Let’s run webpack command, it should be fine now except the warning message about the mode option. Let’s add development as a mode in webpack config.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99364bee028118d83587a6dc3967eaf8/href">https://medium.com/media/99364bee028118d83587a6dc3967eaf8/href</a></iframe><p>Running <em>webpack</em> again and now no more wanring. Run <em>http-server</em> again and we can see “Hello React”.</p><h3>Step 3: Adding more components and support latest ECMA Scripts</h3><p>We are going to add several React components:</p><ul><li>Root: as its name, it will be the Root of all React component in the app.</li><li>Controller: this component has two buttons: Increment, Decrement. As their names, it will increase/decrease one on the counter.</li><li>Displayer: this component will has only one span. It will display the value of the counter.</li></ul><pre>touch ./app/Root.js<br>mkdir ./app/components<br>mkdir ./app/components/Controller<br>touch ./app/components/Controller/index.js<br>touch ./app/components/Controller/controller.presentation.js<br>touch ./app/components/Controller/style.css<br>mkdir ./app/components/Displayer<br>touch ./app/components/Displayer/index.js<br>touch ./app/components/Displayer/displayer.presentation.js<br>touch ./app/components/Displayer/style.css</pre><p>Let’s first modify the <em>index.js</em> in the <em>app</em> folder. We are about to use the Root component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/682770f917a0ab85c192a06db841a37b/href">https://medium.com/media/682770f917a0ab85c192a06db841a37b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21a7edeb3447f3c9f4ad20b0387113d5/href">https://medium.com/media/21a7edeb3447f3c9f4ad20b0387113d5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b32182f7bc59d36ed0b20d1625bff82/href">https://medium.com/media/3b32182f7bc59d36ed0b20d1625bff82/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4721887134bd550cdbadebbe3b3529ef/href">https://medium.com/media/4721887134bd550cdbadebbe3b3529ef/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e5c6b0937a345ac2b826c0c1194eb19/href">https://medium.com/media/3e5c6b0937a345ac2b826c0c1194eb19/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f0f06ef386588e8cf064ce4096f67aa/href">https://medium.com/media/2f0f06ef386588e8cf064ce4096f67aa/href</a></iframe><p>Now if we run <em>webpack</em> and then <em>http-server</em>, we will see something like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Ec6ge4mWE1Vkyi-pdq1DLw.png" /><figcaption>These buttons are not functional now</figcaption></figure><p>Next step is that we will add state and some behaviors for the two buttons. But before we go, let’s add <em>babel-preset-env</em> into our project dependencies so that we can use latest version of ES. If we care about the old browsers and a wide range of browser, then this step might be needed. If we just care about the latest version of popular browsers: Chrome, Safari, Firefox, Edge, then this step is kind of optional because most of them support ES6 which is quite ok from my point of view.</p><pre>npm install --save-dev babel-preset-env</pre><p>We then need to update the babel config in order to use the new Babel preset. Supporting all browser and all versions will increase the build size, so it’s up to us to decide. In the scope of this tutorial, let’s support the latest 2 versions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58dfd2e4ac24de8d6fb7c3c7827fd450/href">https://medium.com/media/58dfd2e4ac24de8d6fb7c3c7827fd450/href</a></iframe><h3>Step 4: Adding redux, redux-thunk, react-redux and connecting redux store with components</h3><p>We will use redux to manage state of the whole app, so let’s install it and then configure the store</p><pre>npm install --save redux</pre><p>Next, let’s create a new file named configStore.js in the <em>app</em> folder — this file is use to configure the redux store</p><pre>touch ./app/configStore.js</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ae6dae0c9bbfae67ac35817c627cc2/href">https://medium.com/media/02ae6dae0c9bbfae67ac35817c627cc2/href</a></iframe><p>In the config above, we are using redux-thunk as a middleware. The thunk is a cool middleware of Redux. With that, we can apply asyn action which can help us in situation that we want to do different works in one action. Let’s say we can fetch data from server, show loading animation, fed the result data into redux store, and then hide the loading anim. Let’s install redux thunk then</p><pre>npm install --save redux-thunk</pre><p>Next is to create rootReducer. In practice, we might organize redux reducer into smaller ones. Let’s go with the following commands to create our reducers</p><pre>mkdir ./app/reducers<br>touch ./app/reducers/index.js<br>touch ./app/reducers/counter.reducer.js</pre><p>We also need some utility functions to help us organize reducer in a better way, so let’s go and create a <em>utils.js</em> file</p><pre>touch ./app/reducers/utils.js</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e1a6e37fe720c6ede31123a642bcf00/href">https://medium.com/media/2e1a6e37fe720c6ede31123a642bcf00/href</a></iframe><p>Now, let’s go back to the reducer <em>counter.reducer </em>and copy the following codes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c16a4df11dda3bf78517663b2c0c59aa/href">https://medium.com/media/c16a4df11dda3bf78517663b2c0c59aa/href</a></iframe><p>The counter reducer handle three actions: increase, decrease, and updateOffset. Initial state of counter reducer is the json object with value=0 and offset = 1. It uses createReducer from utility function we have just created. It also refers to some constants importing from <em>actionTypes/counter.types</em>. Ok, so let’s go and create these constants</p><pre>mkdir ./app/actionTypes<br>touch ./app/actionTypes/counter.types.js</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d93d080c1d6f535bdda9a499525e8ec/href">https://medium.com/media/7d93d080c1d6f535bdda9a499525e8ec/href</a></iframe><p>Now, let’s enter the following code for the <em>index.js</em> inside the <em>reducers</em> folder</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/017168f2bcc4fe7e00bb1b5e5f425e07/href">https://medium.com/media/017168f2bcc4fe7e00bb1b5e5f425e07/href</a></iframe><p>Now, let’s build some actions for the redux store. We are going to add three actions: increaseAsyn, decreaseAsyn, updateOffsetAsyn. These actions are associated with the actions that we are planning to handle in the reducer.</p><pre>mkdir ./app/actions<br>touch ./app/actions/counter.actions.js</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecd8a0995d826b1785ee0a06594dbc5e/href">https://medium.com/media/ecd8a0995d826b1785ee0a06594dbc5e/href</a></iframe><p>Ok cool, the store is set up now. Next step is to connect it with our components. Let’s install react-redux, a tool is recommended by redux team to do this job</p><pre>npm install --save react-redux</pre><p>Let’s go back to the components we created above and modify them in order to connect them with our store.</p><p>Go back to Root component and add <em>Provider</em> component from react-redux to wrap all the child components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/191f3c8afd9cbbed022bed02d24bad11/href">https://medium.com/media/191f3c8afd9cbbed022bed02d24bad11/href</a></iframe><p>Go back to Controller and add mapDispatchToProps in order to dispatch actions to redux store. Let’s open <em>index.js</em> inside <em>Controller</em> folder and modify it as below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab2224853c336a66b42dbb07dcba237/href">https://medium.com/media/aab2224853c336a66b42dbb07dcba237/href</a></iframe><p>Modify the component.presentation in order to dispatch increment/ decrement when user clicks on the buttons</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/456520b4d10431e3218448f2aef64ba0/href">https://medium.com/media/456520b4d10431e3218448f2aef64ba0/href</a></iframe><p>Go back to Displayer and add mapStateToProps in order to map props of component with the store’s state</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5681c715b734a2b01b5acabace7ef2fa/href">https://medium.com/media/5681c715b734a2b01b5acabace7ef2fa/href</a></iframe><p>Now, if we run <em>webpack</em> and then <em>http-server</em>, we will see something like below however this time the buttons become functional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*Ec6ge4mWE1Vkyi-pdq1DLw.png" /><figcaption>These buttons now become functional</figcaption></figure><h3>Step 5: Add webpack hot-module-replacement</h3><p>Right now, if we want to check what we do, we need to do two different commands: webpack and then http-server. Let’s simplify this a little bit by adding the run script in package.json</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3d3cbaebff010bf9d7df87d5112b792/href">https://medium.com/media/d3d3cbaebff010bf9d7df87d5112b792/href</a></iframe><p>Now, let’s try to run npm start, it will first package the files into a bundle and then start a server</p><pre>npm start</pre><p>This is cool, but still we have to run npm start for all the change we want to check. Webpack can do more than that. We can use webpack dev server to enable Hot Module Replacement (HMR) which we could see the change almost instantly after we save a file. HMR is working fine for normal js file it is however not working for react where the rendering mechanic is different. To enable hot reload in react, we also need react-hot-loader which could help us to keep the component’s state as well. Let’s install them first</p><pre>npm install --save-dev webpack-dev-server react-hot-loader</pre><p>To use react-hot-loader, we will need first to update Babel configuration .babelrc to use react-hot-loader plugin</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5337504e0cf2c323b04e39dc1775cf/href">https://medium.com/media/bb5337504e0cf2c323b04e39dc1775cf/href</a></iframe><p>then update the webpack config, let’s add publicPath in the output folder and specify the path as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75b063dc70da69153579e3c9b52b1e05/href">https://medium.com/media/75b063dc70da69153579e3c9b52b1e05/href</a></iframe><p>We also need to update file <em>index.js </em>in the <em>app </em>folder to enable hot reload for all the change under Root component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd626f573748bab6cee9579ee8b34e4/href">https://medium.com/media/5fd626f573748bab6cee9579ee8b34e4/href</a></iframe><p>We also need to change Root component in order to enable react-hot-reload for this component</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/042858762551a6b9aa26aba0734adfa9/href">https://medium.com/media/042858762551a6b9aa26aba0734adfa9/href</a></iframe><p>Now, let’s go back to <em>package.json</em> and change the script to start webpack-dev-server instead of running two commands: webpack and http-server.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e57b75bfed4461ac0ee77ec871bff4d/href">https://medium.com/media/3e57b75bfed4461ac0ee77ec871bff4d/href</a></iframe><p>Let’s start the server</p><pre>npm start</pre><p>…and then make some change in file displayer.presentation to see if it works</p><h3>Step 6: Prepare for development and production environment with webpack</h3><p>In practice, we should separate build for production and for development. The first one should be minified, obfuscated, and built with optimized source map. The second one on the other hand should be built without obfuscate/minify and with the appropriate source map as well.</p><p>Let’s reorganize our webpack config file. In stead of having only one for now, we will separate it into three different files: 1) webpack.common.js — to share the same setting between production and development. 2) webpack.production.js, 3) webpack.development.js. We will need webpack-merge in order to merge the common config into either production/development configuration.</p><pre>touch webpack.common.js<br>touch webpack.development.js<br>touch webpack.production.js<br>npm install --save-dev webpack-merge</pre><p>For production build, we will use uglifyjs-webpack-plugin in order to deal with minifying/obfuscating. We will also try to set the NODE_ENV to “production” which could help us to check if the build is running in production mode or not. Now, let’s install uglifyjs-web-pack-plugin</p><pre>npm install --save-dev uglifyjs-webpack-plugin</pre><p>Before we set up the webpack config let’s install the clean-webpack-plugin. It is to ensure that the <em>dist</em> folder will be cleaned before webpack actually build the source.</p><pre>npm install --save-dev clean-webpack-plugin</pre><p>Ok, let’s configure the webpack configuring files that we created above</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/311d0d1909dbda2cdb8ce06345191519/href">https://medium.com/media/311d0d1909dbda2cdb8ce06345191519/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295ab8d78274a7858e12985ab848f73b/href">https://medium.com/media/295ab8d78274a7858e12985ab848f73b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bdde0ec326e93e47f440bd6d1b02c13/href">https://medium.com/media/1bdde0ec326e93e47f440bd6d1b02c13/href</a></iframe><p>Cool, now let’s go back to package.json and change the run script as well as add a new build script</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6a23b1e6fb3c9123fbbec42e26493b7/href">https://medium.com/media/b6a23b1e6fb3c9123fbbec42e26493b7/href</a></iframe><p>Now, if we run <strong>npm start</strong>, it will start webpack-dev-server using the configuration in <em>webpack.development.js</em>. If we run <strong>npm run build</strong>, it will build the project using the configuration described in the file <em>webpack.production.js</em></p><p>Let’s remove the old webpack.config.js, we don’t need it anymore</p><pre>rm webpack.config.js</pre><h3>Step 7: Add webpack loader for css and add babel plug-in to reduce the verbose of Object.atssign in redux reducer</h3><p>Because we are working on a SPA, CSS is something that we will need for sure. Let’s go back to the two styles.css files located in Controller and Displayer components that we created in step 3. Let’s revisit the Controller component and add some styles as well as import the style into the file <em>controller.presentation.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61a4bf8c0b1d6fe7e580362f6ea9dcf2/href">https://medium.com/media/61a4bf8c0b1d6fe7e580362f6ea9dcf2/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3e783d6ec4c7f18e8f63e86431cfe13/href">https://medium.com/media/a3e783d6ec4c7f18e8f63e86431cfe13/href</a></iframe><p>If we run <strong>npm start, </strong>we will get the error below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDBfkb8vtPLUOUUXVUJaLQ.png" /></figure><p>It’s because there is no loader configured for webpack to load css. To have css working fine, we need two loaders: CSS and Style loader. Let’s install both of them and then configure webpack config to use the new installed loaders.</p><pre>npm install --save-dev css-loader style-loader</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54bd591c510d1e33259c7b3dbf4692fb/href">https://medium.com/media/54bd591c510d1e33259c7b3dbf4692fb/href</a></iframe><p>Let’s rerun the command <strong>npm start</strong>, it should be fine now.</p><p>And now, go back to Displayer component and add some styles as well as import it into the file <em>displayer.presentation.js</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cacd1a15d21f3d5313e19c02d58f5847/href">https://medium.com/media/cacd1a15d21f3d5313e19c02d58f5847/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6630dc3da35a0cee0ff376e8fd8952e/href">https://medium.com/media/b6630dc3da35a0cee0ff376e8fd8952e/href</a></iframe><p>Let’s run <strong>npm start </strong>again, it should be fine this time.</p><p>Since state is immutable in react and redux, we normally have two options to go: either we go with immutable lib or we go with Object.assign. For the scope of this guide, we just use Object.assign. We can use babel plug-in babel-plugin-transform-object-rest-spread to replace it. Let’s go first by adding the lib to our project’s dependencies</p><pre>npm install --save-dev babel-plugin-transform-object-rest-spread</pre><p>And then modify the .babelrc file to add this plugin</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a0a749c3017c5487fc9a1a79d1211a3/href">https://medium.com/media/3a0a749c3017c5487fc9a1a79d1211a3/href</a></iframe><p>Now, let’s go back to the <em>counter.reducer.js</em> and replace Object.assign by the spread operator</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e55b0040590bcd13391662f1b590075/href">https://medium.com/media/5e55b0040590bcd13391662f1b590075/href</a></iframe><p>If we run <strong>npm start</strong> now, we can see the app is still fine.</p><h3>Step 8: Adding redux dev tool in order to check the redux state while debugging</h3><p>Now, the final step of this guide is to add redux dev tool in order to <em>see </em>the detail of the redux state at run time</p><p>There is a Chrome extension that could help us to do this — two things we need to do: 1) following the instruction <a href="https://github.com/zalmoxisus/redux-devtools-extension">here</a> to install the extension in Chome, 2) and then modify createStore a little bit.</p><pre>npm install --save-dev redux-devtools-extension</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f936e32f1ed0a187f10ac06803b49ba2/href">https://medium.com/media/f936e32f1ed0a187f10ac06803b49ba2/href</a></iframe><p>Now, if we open redux extension in Chrome, we can see everything in the redux store.</p><p>Congratulation, we now have everything set up. You can check the source full in here</p><p><a href="https://github.com/tamdang/my_react_boilerplate">tamdang/my_react_boilerplate</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b81f258ccbe1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An attempt to build react-redux myself]]></title>
            <link>https://medium.com/@dangthanhtam/an-attempt-to-build-react-redux-myself-1b0ddf338e38?source=rss-46f5d611191e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b0ddf338e38</guid>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Dang Thanh Tam]]></dc:creator>
            <pubDate>Thu, 15 Mar 2018 08:24:19 GMT</pubDate>
            <atom:updated>2018-03-15T23:57:55.661Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*42EwefjpTHcGIoXJP-N3tg.jpeg" /></figure><p>I have been working in React for around two years. As many other react developers, I was using redux to manage state and react-redux for binding redux store and component. React-redux in fact saves a lot of time for manually passing redux store to all components. One question came into my mind was that how react-redux’s <em>connect</em> function does the binding magic. That function does not require a reference to redux store then how it can do the magic in <em>mapStateToProps</em> and <em>mapDispatchToProps. </em>There should be a way for that function to get a reference to the redux store, otherwise the magic would not happen.</p><p>I decided some days ago that I would implement a react-redux myself. The aim is not to build a new lib but to understand react deeper. I decided to not check the react-redux code at all but try to do it from scratch. After checking React document further, I noticed that there is something that I have never tried before and that is Context. Though React strongly suggest NOT to use it, it is actually what being used in order to build react-redux. I will go through the steps I took to build my own lib. Because it’s just an experimental, I decided to use Codepen.</p><p>By end of this article we will have something like below. The dependencies on Codepen will include: react, react-dom, redux, prop-types. We also need to add Babel as a Preprocessor</p><h3>Create a pure React app without Redux</h3><p>First create a pen, then add the following external scripts: react, react-dom. Add Babel as JavaScript preprocessor</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*G2PbXLIdJTay-eup84Nq9A.png" /><figcaption>External scrips and preprocessor</figcaption></figure><p>Add a div in HTML with the id as <em>root</em></p><pre>&lt;div id=&#39;root&#39;&gt;&lt;/div&gt;</pre><p>Add components to render the react component into the <em>root</em> div</p><pre>const Controller = () =&gt; (<br>  &lt;div&gt;<br>    &lt;button&gt;Increase&lt;/button&gt;<br>    &lt;button&gt;Decrease&lt;/button&gt;<br>  &lt;/div&gt;<br>)</pre><pre>const Displayer = ({counter}) =&gt; (<br>  &lt;div&gt;<br>    &lt;span&gt;{counter}&lt;/span&gt;<br>  &lt;/div&gt;<br>)</pre><pre>const App = () =&gt; (<br>  &lt;div&gt;<br>    &lt;Controller/&gt;<br>    &lt;Displayer counter={0}/&gt;<br>  &lt;/div&gt;<br>)</pre><pre>ReactDOM.render(&lt;App/&gt;, document.getElementById(&#39;root&#39;))</pre><p>At this step, you will see in the result view there are two buttons: Increase and Decrease. And the number zero below the two buttons.</p><h3>Adding Redux to manage state</h3><p>First we will add Redux as dependency in Codepen</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*Y_tfGmkak-4VOay14vS0Aw.png" /></figure><p>We will then add codes to setup redux store</p><pre>const defaultState = {counter: 0}<br>const React = window.React<br>const {createStore} = window.Redux<br>const PropTypes = window.PropTypes</pre><pre>const increment = {type: &#39;INCREMENT&#39;}<br>const decrement = {type: &#39;DECREMENT&#39;}</pre><pre>const reducer = (state, action) =&gt; {<br>  switch(action.type){<br>    case &#39;INCREMENT&#39;:<br>      return {counter: state.counter + 1}<br>    case &#39;DECREMENT&#39;:<br>      return {counter: state.counter -1}<br>    default:<br>      return state<br>  }<br>}</pre><pre>const store = createStore(reducer, defaultState)</pre><h3>Create a connect function</h3><p>We will create a Container inside the connect function. Container will render the input component whenever the props mapped into the redux state change. Several things the Container needs to do in order to achieve that:</p><ul><li>Get the reference to the redux store. This is done by using the React Context</li></ul><pre>Container.contextTypes = {myStore: PropTypes.object}</pre><ul><li>Create its own state and ensure it state map with the properties passed into the mapStateToProps object</li></ul><pre>this.state = Object.assign({},mapStateToProps(this.myStore.getState()))<br>      }</pre><ul><li>Register a listener to the redux store</li></ul><pre>context.myStore.subscribe(this.onReduxStateChange)</pre><ul><li>Update container state whenever the redux state change, hence trigger the render function to render the input component</li><li>Set the dispatcher functions based on the json object declared in the <em>mapDispatchToProps</em></li><li>Pass all the props declared into the <em>mapStateToProps </em>and dispatch functions declared in <em>mapDispatchToProps </em>into the input component in render function</li></ul><pre>&lt;Component {...this.state}{...this.dispatches}/&gt;</pre><p>Since React Context need to define the PropTypes, we will need to add it as dependency</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*R6HvhnYBiiqF2JgfchNFug.png" /></figure><p>And now the full source of the <em>connect </em>function</p><pre>const connect = (mapStateToProps, mapDispatchToProps) =&gt; Component =&gt; {<br>  class Container extends React.Component{<br>    constructor(props, context){<br>      super()<br>      this.onReduxStateChange = this.onReduxStateChange.bind(this)<br>      this.myStore = context.myStore<br>      context.myStore.subscribe(this.onReduxStateChange)<br>      if(mapStateToProps){<br>         this.state = Object.assign({},mapStateToProps(this.myStore.getState()))<br>      }<br>      this.dispatches = {}<br>      if(mapDispatchToProps){<br>        Object.keys(mapDispatchToProps).map(k=&gt;this.dispatches[k]=()=&gt;this.myStore.dispatch(mapDispatchToProps[k]))<br>      }<br>    }<br>    render(){<br>      return (<br>        &lt;div&gt;<br>          &lt;Component {...this.state}{...this.dispatches}/&gt;<br>        &lt;/div&gt;<br>      )<br>    }<br>    onReduxStateChange(){<br>      if (this.state){<br>        this.setState(mapStateToProps(this.myStore.getState()))        <br>      }<br>    }<br>  } <br>  Container.contextTypes = {myStore: PropTypes.object}<br>  return Container<br>}</pre><h3>Create a store provider</h3><p>To pass the store object to all the components we will build a Parent component, called StoreProvider. That component will set the redux store to Context. It’s then all the child components will have the access to it. The StoreProvider will have <em>store </em>as a prop.</p><pre>class StoreProvider extends React.Component {<br>  getChildContext(){<br>    return {myStore: this.store}<br>  }<br>  constructor(props){<br>    super()<br>    this.child = props.children<br>    this.store = props.store<br>  }<br>  render(){<br>    return (<br>      &lt;div&gt;<br>        {this.child}<br>      &lt;/div&gt;<br>    )<br>  }<br>}<br>StoreProvider.childContextTypes = { myStore: PropTypes.object}</pre><h3>Using the StoreProvider component and connect function</h3><p>Let’s bind the store and state, dispatch using our connect function</p><pre>const mapStateToProps = state =&gt; ({<br>  counter: state.counter<br>})</pre><pre>const mapDispatchToProps = {<br>  increment: increment,<br>  decrement: decrement<br>}</pre><pre>const ContainerDisplayer = connect(mapStateToProps, null)(Displayer)<br>const ContainerController = connect(null, mapDispatchToProps)(Controller)</pre><p>Update the Controller component to add dispatch</p><pre>const Controller = (props) =&gt; (<br>  &lt;div&gt;<br>    &lt;button onClick={()=&gt;props.increment()}&gt;Increase&lt;/button&gt;<br>    &lt;button onClick={()=&gt;props.decrement()}&gt;Decrease&lt;/button&gt;<br>  &lt;/div&gt;<br>)</pre><p>Update the App component to add StoreProvider component as the parent component.</p><pre>const App = () =&gt; (<br>  &lt;StoreProvider store={store}&gt;<br>    &lt;div&gt;<br>      &lt;ContainerController/&gt;<br>      &lt;ContainerDisplayer counter={0}/&gt;<br>    &lt;/div&gt;<br>  &lt;/StoreProvider&gt;<br>)</pre><p>Now, if you check the result view, you can click on the button increase/decrease to change the value of the counter.</p><p>The react-redux is much more complicated than the code I’m doing and it is optimized to increase the performance. The code here is just an attempt to understand more about the library. Check the whole source code below and enjoy!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fdangtam%2Fembed%2Fpreview%2FwmGxqP%3Fheight%3D600%26slug-hash%3DwmGxqP%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fdangtam%2Fpen%2FwmGxqP%3Feditors%3D1011&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1653507.wmGxqP.small.12d1e386-c407-4e29-8bdd-86967dcb5956.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/03f98919c646ff9eee0ee3893fc040ab/href">https://medium.com/media/03f98919c646ff9eee0ee3893fc040ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b0ddf338e38" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>