<?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 Valentyn Bilousov on Medium]]></title>
        <description><![CDATA[Stories by Valentyn Bilousov on Medium]]></description>
        <link>https://medium.com/@valentynbilousov?source=rss-86c2089b4762------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*sqNnB8Zi3T9HX2KUow57tQ.jpeg</url>
            <title>Stories by Valentyn Bilousov on Medium</title>
            <link>https://medium.com/@valentynbilousov?source=rss-86c2089b4762------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:39:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valentynbilousov/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[Hide security credentials in AWS Elastic Beanstalk environment with KMS and S3 bucket]]></title>
            <link>https://medium.com/@valentynbilousov/hide-security-credentials-in-aws-elastic-beanstalk-environment-with-kms-and-s3-bucket-f7d1e164432e?source=rss-86c2089b4762------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7d1e164432e</guid>
            <category><![CDATA[key-management-service]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[s3]]></category>
            <category><![CDATA[elastic-beanstalk]]></category>
            <category><![CDATA[aws-kms]]></category>
            <dc:creator><![CDATA[Valentyn Bilousov]]></dc:creator>
            <pubDate>Sat, 16 May 2020 05:51:28 GMT</pubDate>
            <atom:updated>2020-05-16T05:56:12.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*pja68l0Uk_Oh7UW9OtHVWA.png" /></figure><p>In this article I will show, how to keep sensitive information (like database credentials) private in your elastic beanstalk environment. To follow all the next steps, you need to have an AWS account, which is easy to set up. Also your account needs to have permissions to next aws services: Elastic Beanstalk, S3, Key Management Service, IAM and Lambda (we will use it to encrypt our data).</p><p>We will use S3 bucket to keep this information and AWS Key Management Service to make it encrypted. There are multiple ways to encrypt our information, but for this article I decided to choice Lambda function. As an example, I decided to create EB environment on regular python platform and deploy a simple flask app. To make it simple, we won’t use any AWS CLI, so we don’t need to set up configurations for our account. At first, we will create our Elastic Beanstalk environment, S3 bucket, custom managed key in KMS and lambda function, to encrypt our data. After that we will set up all configurations to manage it. So, let’s get started.</p><p>NOTE: We need to pay for all AWS services we using. Although, most of them got very generous trial, make sure that you are not running services that you are not using.</p><h3>Create a simple Flask App and deploy it to Elastic Beanstalk</h3><p>I decide to use regular flask app, which is provided by AWS official documentation <a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-flask.html">here</a>. My source code you can find on a github on <a href="https://github.com/bilousov94/aws_eb_kms">master</a> branch. If everything is correct and you have all libraries installed, you can test this application locally by running command in your project root directory with command</p><pre>python application.py</pre><p>After that in console you should see the link. Navigate to this link and you will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*bwt-aZJL4HlBUeOJmIvvbQ.png" /></figure><p>We created a simple flask app and we are ready to deploy it to AWS Elastic Beanstalk. In AWS console, navigate to service Elastic Beanstalk. Create a simple environment on Python platform. Also, compress our application.py and requirements.txt into .zip and upload this archive to our environment. The rest, you can leave as default and create environment.</p><p>NOTE: If your environment not working, try to update your environment Software configurations WSGIPath to application:application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mByS-pTkYo2DnTI5n943SQ.png" /></figure><p>If everything fine, you should see that your environment created and AWS will provide a link to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_1s2F1KyJkMcrEmip0j0A.png" /></figure><h3>Set the rest of resources (s3, lambda, kms )</h3><p>For generating our encrypted file, I decided to choose lambda function and to store this data we will use S3 bucket. In this part we will create a simple lambda function on python and S3 bucket.</p><p>Now, navigate to AWS S3 service and click create bucket. Use all default settings (make sure that you blocked all public access). Also, bucket name should be globally unique. For my bucket I selected the name eb-secret-bucket , but your one will be with different name. After you will create this bucket, make sure that he is displayed in list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0tyfqLV_WfQnHnSjmbjfA.png" /></figure><p>Next, navigate to AWS Lambda service and click create function. Create the new function from scratch. Then select name and language for function. My function called eb-secret-bucket and I select Python 3.8 for it. For function code you can use this github <a href="https://gist.github.com/bilousov94/3cff4aca6c8726dee4188a89de28e380">gist</a> or paste next code and click save:</p><pre>import json<br>import boto3<br>import base64def lambda_handler(event, context):<br>    <br>    # data, which we will encrypt<br>    mydata = {<br>        &quot;secret&quot;: &quot;something important&quot;, <br>        &quot;password&quot;: &quot;very_secret_password&quot;, <br>    }    kms = boto3.Session().client(&#39;kms&#39;)<br>    <br>    #encrypt the data<br>    ciphertext = kms.encrypt(<br>        KeyId=&#39;alias/eb-secret&#39;, <br>        Plaintext=json.dumps(mydata)<br>    )<br>    <br>    encoded_ciphertext = base64.b64encode(ciphertext[&quot;CiphertextBlob&quot;])<br>    <br>    s3 = boto3.Session(region_name=&#39;us-east-1&#39;).client(&#39;s3&#39;)<br>    <br>    #put encrypted data into s3 bucket<br>    response = s3.put_object(<br>        Body=encoded_ciphertext, <br>        Bucket=&#39;eb-secret-bucket&#39;, <br>        Key=&#39;secret_data.json&#39;,<br>    )<br>    <br>    print(response)</pre><p>NOTE: This function won’t work now. Our Lambda doesn’t have any permissions to work with S3 bucket and KMS. We will go back to this later.</p><p>Remember, we will use lambda function just to encrypt our secrets and put it in S3 bucket. So, if everything is correct, you should see lambda function in your list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxZLNWnwSQl207HaemLF9A.png" /></figure><p>Now, navigate to AWS Key Management Service. Under tab Customer managed keys press <strong>Create Key</strong>. Now follow these 5 steps:</p><ol><li>Configure key — select Symmetric for key type</li><li>Add labels — add key name and description</li><li>Key administrative permissions — from list of users and roles, select the key admin or just click next and go for next step</li><li>Key usage permissions — you can click next and go to the next step. We will create our own policies to manage our resources</li><li>Review key policy — you should review your key policy. Key policy should be very short, because we will manage them in the next step. My policy looks like that (you can copy it):</li></ol><pre>{<br>    &quot;Id&quot;: &quot;key-consolepolicy-3&quot;,<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;Enable IAM User Permissions&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: {<br>                &quot;AWS&quot;: &quot;arn:aws:iam::&lt;YOUR_ACCOUNT_ID&gt;:root&quot;<br>            },<br>            &quot;Action&quot;: &quot;kms:*&quot;,<br>            &quot;Resource&quot;: &quot;*&quot;<br>        }<br>    ]<br>}</pre><p>After you clicked finish, you can observe your key in a list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIpt8KIixJ2v8rJZgXP10g.png" /></figure><h3>Create IAM policies</h3><p>Now, when we have working Elastic Beanstalk environment, KMS key, Lambda function for creating encrypted file and S3 for keeping this file, we need to create new IAM policies and attach it to our resources.</p><p>Navigate now to AWS IAM service. Under policies tab, click <strong>Create policy </strong>button. First, we will create a policy for our encrypt-secrets lambda function. So, in a JSON tab paste next:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:PutObject&quot;,<br>                &quot;kms:Encrypt&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:kms:us-east-1:&lt;YOUR_ACCOUNT_ID&gt;:key/&lt;YOUR_KEY_ID&gt;&quot;,<br>                &quot;arn:aws:s3:::eb-secret-bucket/*&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>NOTE: You can find &lt;YOUR_KEY_ID&gt; on KMS page. Select Key ID for your key and paste it in policy.</p><p>When everything is ready, select name for your policy and create it. For my policy I selected Lambda-kms-s3 . This policy allows to use our kms key to encrypt the data and store it in eb-secret-bucket S3 bucket. Now we will create a policy which allows to get data from eb-secret-bucket and use kms key to decrypt it. So, create new policy eb-decrypt and paste next json into it:</p><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;VisualEditor0&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Action&quot;: [<br>                &quot;s3:GetObject&quot;,<br>                &quot;kms:Decrypt&quot;<br>            ],<br>            &quot;Resource&quot;: [<br>                &quot;arn:aws:s3:::eb-secret-bucket/*&quot;,<br>                &quot;arn:aws:kms:us-east-1:&lt;YOUR_ACCOUNT_ID&gt;:key/&lt;YOUR_KEY_ID&gt;&quot;<br>            ]<br>        }<br>    ]<br>}</pre><p>When all our policies created, we can attach them to our roles.</p><h3>Attach IAM policies to existing roles</h3><p>Navigate to AWS IAM service. Under <strong>Roles</strong> tab find the role for lambda, which you created in previous step (you can get the name of role on lambda function page under <strong>Permissions</strong> tab). After that, select this role and attach our encrypt-secrets policy to it (or the name you’ve selected). Next, we need to add new policy to our Elastic Beanstalk instance.</p><p>Navigate to Elastic Beanstalk service and select environment, you created in previous step. Under the security configurations you can find the role, which elastic beanstalk attached to instance it created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b99GxYagpMPXN3XlXjAniw.png" /></figure><p>Now, when we know the name of role, we can go back to IAM roles and attach policy. So select this role from list and attach our eb-decrypt policy to it. Now we got everything we need. Lambda function can encrypt end put file in S3 and EB instance can get this file from S3 and decrypt. Let’s check if it works in the next step.</p><h3>Decrypt and display data in app</h3><p>At first, we start with running our lambda function. This function will encrypt some data and will store it in S3 bucket in secret_data.json file. You can observe what data we will encrypt in function body. Navigate to list of lambda functions and select one you created ( in my case it is encrypt-secrets). On top right corner click test and this will prompt you to create a test. You can leave the body of test as an empty object, like {} , we won’t expect any parameters. Then click create and test.</p><p>NOTE: with AWS Lambda, you are charged for the invocation requests as well as the duration of the invocations.</p><p>Once you run lambda one time, you should see in your S3 bucket new file, which called secret_data.json . If you will download this file, you will see that it is encrypted and all data make no sense. In next step we will modify source code of our Elastic Beanstalk application to read and decrypt this data.</p><p>Now we need to modify our original flask application code so it could get object from S3 bucket, which we created with lambda, decrypt it with kms and display it key-values. We need to add next code snippet into application.py file:</p><pre>kms = boto3.Session(region_name=&#39;us-east-1&#39;).client(&#39;kms&#39;)<br>s3 = boto3.Session(region_name=&#39;us-east-1&#39;).client(&#39;s3&#39;)<br><br># get file from s3 bucket<br>file = s3.get_object(Bucket=&#39;eb-secret-bucket&#39;, Key=&#39;secret_data.json&#39;)<br><br>secret = file[&#39;Body&#39;].read()<br><br>decoded_secret = base64.b64decode(secret)<br><br># decrypt file with kms<br>decrypted_secret = kms.decrypt(CiphertextBlob=bytes(decoded_secret))<br><br>secret = json.loads(decrypted_secret[&quot;Plaintext&quot;])</pre><p>NOTE: This is a peace of code which we need to add, but all source code you can find on github in <a href="https://github.com/bilousov94/aws_eb_kms/tree/secret_display">secret_display</a> branch. Don’t forget to install and add <strong>boto3 </strong>library to your app.</p><p>After you’ve done with all changes compress application.py and requirements.txt .zip file and upload it to Elastic Beanstalk environment. If everything is correct, navigate to link for Eb environment. You should see something familiar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmgtNNq_oJuw25PWs2j58A.png" /></figure><h3>Summary</h3><p>All final code for flask app you can find on my <a href="https://github.com/bilousov94/aws_eb_kms">GitHub repo.</a> All code for lambda function you can find on <a href="https://gist.github.com/bilousov94/3cff4aca6c8726dee4188a89de28e380">Github gist</a>. This is one of the simplest ways to hide you secrets not just for Elastic Beanstalk environment, but also for other resources. Feel free to experimenting.</p><p>I hope that this article will help you. I’m curious to know also about other interesting ways to do this. Please let me know what you think in the comments below.</p><p>🎉Happy coding🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7d1e164432e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing data between sibling components in React using Context API and React Hooks]]></title>
            <link>https://itnext.io/passing-data-between-sibling-components-in-react-using-context-api-and-react-hooks-fce60f12629a?source=rss-86c2089b4762------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce60f12629a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[context-api]]></category>
            <dc:creator><![CDATA[Valentyn Bilousov]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 21:08:13 GMT</pubDate>
            <atom:updated>2019-10-08T07:34:48.474Z</atom:updated>
            <content:encoded><![CDATA[<p>I will build a simple react app with 2 inputs, where their values will be completely synchronized. In this article I will explain how easy to send data between react sibling components using the most recent react features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FdSxEIpAJFkZgDE5AwJzbA.png" /></figure><h3>Set up React environment</h3><p>To start the new app in react, you don’t need to worry about all settings and configurations. I will use Create React App environment, which is pretty simple and well documented. All documentation about this toolchain you can find <a href="https://reactjs.org/docs/create-a-new-react-app.html">here</a>.</p><p>Create react project</p><pre>npx create-react-app sync_inputs</pre><p>After that you need to navigate to folder sync_inputs and start the app</p><pre>cd sync_inputs<br>npm start</pre><p><strong><em>Note: </em></strong>You might have some problems with running this local server. If you have an error message like<strong><em> </em></strong>Attempting to bind to HOST environment variable: <strong>x86_64-apple-darwin13.4.0 </strong>, then<strong> </strong><a href="https://medium.com/@choy/fixing-create-react-app-when-npm-fails-to-start-because-your-host-environment-variable-is-being-4c8a9fa0b461">this</a> article might be helpful for you. When I tried to run my server, I had an error TypeError: fsevents is not a constructor. I found a lot of advices how to deal with it <a href="https://github.com/facebook/create-react-app/issues/6891">here</a>, but personally for me helped to remove all node packages and run again npm install . After that I run npm start and everything worked. Also, using npm is not necessary. You can use yarn if you like it more.</p><p>If everything is installed and your local server is running, you need to navigate http://localhost:3000 and you should see react logo on dark background. Something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z84fKweil9V5z2XAO0EUxQ.png" /></figure><p>Now stop the local server by press ctrl + c in your terminal and install couple more dependencies.</p><p>Install <a href="https://material-ui.com/">Material UI</a> core library and their icon library for making nice UI</p><pre>npm install @material-ui/core<br>npm install @material-ui/icons</pre><p>Now your <em>package.json</em> file should looks like this:</p><pre>{<br>  &quot;name&quot;: &quot;sync_inputs&quot;,<br>  &quot;version&quot;: &quot;0.1.0&quot;,<br>  &quot;private&quot;: <strong>true</strong>,<br>  &quot;dependencies&quot;: {<br>    &quot;@material-ui/core&quot;: &quot;^4.5.0&quot;,<br>    &quot;@material-ui/icons&quot;: &quot;^4.4.3&quot;,<br>    &quot;react&quot;: &quot;^16.10.2&quot;,<br>    &quot;react-dom&quot;: &quot;^16.10.2&quot;,<br>    &quot;react-scripts&quot;: &quot;3.2.0&quot;<br>  },<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;react-scripts start&quot;,<br>    &quot;build&quot;: &quot;react-scripts build&quot;,<br>    &quot;test&quot;: &quot;react-scripts test&quot;,<br>    &quot;eject&quot;: &quot;react-scripts eject&quot;<br>  },<br>  &quot;eslintConfig&quot;: {<br>    &quot;extends&quot;: &quot;react-app&quot;<br>  },<br>  &quot;browserslist&quot;: {<br>    &quot;production&quot;: [<br>      &quot;&gt;0.2%&quot;,<br>      &quot;not dead&quot;,<br>      &quot;not op_mini all&quot;<br>    ],<br>    &quot;development&quot;: [<br>      &quot;last 1 chrome version&quot;,<br>      &quot;last 1 firefox version&quot;,<br>      &quot;last 1 safari version&quot;<br>    ]<br>  }<br>}</pre><p>So, now we have our working environment with all libraries, which we need. Now it is time for start building our app.</p><h3><strong>Create React Components</strong></h3><blockquote>In this part I will set up our project structure and will create all UI.</blockquote><p>First, create new folder components in ./src directory of our project. After that in ./src/components create two new components (<em> Input_one.js</em>, <em>Input_two.js</em> ). After all these steps, your project structure should looks like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*IPpFSBNUuiiKDolHtlTNfA.png" /></figure><p>In next steps I will modify our components to create a nice UI.</p><p>Modify ./src/components/Input_one.js to create an input one.</p><pre><strong>import </strong>React <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{makeStyles} <strong>from </strong>&quot;@material-ui/core/styles/index&quot;;<br><br>//Material UI components<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>Paper <strong>from </strong>&#39;@material-ui/core/Paper&#39;;<br><strong>import </strong>InputBase <strong>from </strong>&#39;@material-ui/core/InputBase&#39;;<br><br>//Material UI Icons<br><strong>import </strong>IconButton <strong>from </strong>&#39;@material-ui/core/IconButton&#39;;<br><strong>import </strong>SearchIcon <strong>from </strong>&#39;@material-ui/icons/Search&#39;;<br><br><strong>const </strong>useStyles = makeStyles({<br>    root: {<br>        padding: &#39;2px 4px&#39;,<br>        display: &#39;flex&#39;,<br>        alignItems: &#39;center&#39;,<br>        width: &#39;100%&#39;,<br>    },<br>    input: {<br>        marginLeft: &#39;8px&#39;,<br>        flex: 1,<br>    },<br>    iconButton: {<br>        padding: 10,<br>    }<br>});<br><br><strong>export default function </strong>Input_one() {<br>    <strong>const </strong>classes = useStyles();<br><br>    <strong>return</strong>(<br>        &lt;React.Fragment&gt;<br>            &lt;Grid item xs={12} md={6}&gt;<br>                &lt;Paper className={classes.root}&gt;<br>                    &lt;InputBase<br>                        className={classes.input}<br>                        placeholder=&quot;Input one&quot;<br>                    /&gt;<br>                    &lt;IconButton className={classes.iconButton} aria-label=&quot;search&quot;&gt;<br>                        &lt;SearchIcon /&gt;<br>                    &lt;/IconButton&gt;<br>                &lt;/Paper&gt;<br>            &lt;/Grid&gt;<br>        &lt;/React.Fragment&gt;<br>    )<br>}</pre><p>Modify ./src/components/Input_two.js to create an input two.</p><pre><strong>import </strong>React <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{makeStyles} <strong>from </strong>&quot;@material-ui/core/styles/index&quot;;<br><br>//Material UI components<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>Paper <strong>from </strong>&#39;@material-ui/core/Paper&#39;;<br><strong>import </strong>InputBase <strong>from </strong>&#39;@material-ui/core/InputBase&#39;;<br><br>//Material UI Icons<br><strong>import </strong>IconButton <strong>from </strong>&#39;@material-ui/core/IconButton&#39;;<br><strong>import </strong>SearchIcon <strong>from </strong>&#39;@material-ui/icons/Search&#39;;<br><br><strong>const </strong>useStyles = makeStyles({<br>    root: {<br>        padding: &#39;2px 4px&#39;,<br>        display: &#39;flex&#39;,<br>        alignItems: &#39;center&#39;,<br>        width: &#39;100%&#39;,<br>    },<br>    input: {<br>        marginLeft: &#39;8px&#39;,<br>        flex: 1,<br>    },<br>    iconButton: {<br>        padding: 10,<br>    }<br>});<br><br><strong>export default function </strong>Input_two() {<br>    <strong>const </strong>classes = useStyles();<br><br>    <strong>return</strong>(<br>        &lt;React.Fragment&gt;<br>            &lt;Grid item xs={12} md={6}&gt;<br>                &lt;Paper className={classes.root}&gt;<br>                    &lt;InputBase<br>                        className={classes.input}<br>                        placeholder=&quot;Input two&quot;<br>                    /&gt;<br>                    &lt;IconButton className={classes.iconButton} aria-label=&quot;search&quot;&gt;<br>                        &lt;SearchIcon /&gt;<br>                    &lt;/IconButton&gt;<br>                &lt;/Paper&gt;<br>            &lt;/Grid&gt;<br>        &lt;/React.Fragment&gt;<br>    )<br>}</pre><p><strong><em>Note:</em></strong> <em>Input_one</em> and <em>Input_two </em>components are almost the same. Now the main difference in export default function Input_one() and export default function Input_two()</p><p>Now modify ./src/App.js file. In this file I will create <em>Container</em>, where will be stored all content of our app, add title and import our <em>&lt;Input_one/&gt;</em> and <em>&lt;Input_two/&gt;</em> components.</p><pre><strong>import </strong>React <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{ makeStyles } <strong>from </strong>&#39;@material-ui/core/styles&#39;;<br><br>//Material UI components<br><strong>import </strong>Container <strong>from </strong>&#39;@material-ui/core/Container&#39;;<br><strong>import </strong>Typography <strong>from </strong>&#39;@material-ui/core/Typography&#39;;<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>CssBaseline <strong>from </strong>&#39;@material-ui/core/CssBaseline&#39;;<br><strong>import </strong>Toolbar <strong>from </strong>&#39;@material-ui/core/Toolbar&#39;;<br><br>//Import our Inputs<br><strong>import </strong>Input_one <strong>from </strong>&#39;./components/Input_one&#39;;<br><strong>import </strong>Input_two <strong>from </strong>&#39;./components/Input_two&#39;;<br><br>//Styles<br><strong>const </strong>useStyles = makeStyles({<br>    toolbarTitle: {<br>        flex: 1,<br>    },<br>});<br><br><strong>function </strong>App() {<br><br>  <strong>const </strong>classes = useStyles();<br><br>  <strong>return </strong>(<br>      &lt;Container maxWidth=&quot;lg&quot;&gt;<br>          &lt;CssBaseline /&gt;<br><br>          {/*Title*/}<br>          &lt;Toolbar&gt;<br>              &lt;Typography<br>                  component=&quot;h2&quot;<br>                  variant=&quot;h5&quot;<br>                  color=&quot;inherit&quot;<br>                  align=&quot;center&quot;<br>                  noWrap<br>                  className={classes.toolbarTitle}<br>              &gt;<br>                  Pass data between react sibling components<br>              &lt;/Typography&gt;<br>          &lt;/Toolbar&gt;<br><br>          {/*Inputs*/}<br>          &lt;Grid container spacing={1}&gt;<br>              &lt;Input_one/&gt;<br>              &lt;Input_two/&gt;<br>          &lt;/Grid&gt;<br><br>      &lt;/Container&gt;<br>  );<br>}<br><br><strong>export default </strong>App;</pre><p>After all these steps, navigate to http://localhost:3000 . Our project should looks like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SaCVYnxDFXme8k8pL2ciMQ.png" /></figure><h3>Create functionality to pass data between components</h3><p>According to React <a href="https://reactjs.org/docs/context.html">documentation</a></p><blockquote>Context is primarily used when some data needs to be accessible by <em>many</em> components at different nesting levels.</blockquote><p>In ./src/App.js create a context object</p><pre>// Create context object<br><strong>export const </strong>AppContext = React.createContext();</pre><p>Then set Initial state object, where we store our date, which should be accessible from both Inputs.</p><pre>// Set up Initial State<br><strong>const </strong>initialState = {<br><br>    inputText: &#39;&#39;,<br><br>};</pre><p>Now create function reducer , which will update our initial state every time, when the value of any inputs will be changed. We will use this function with useReducer</p><pre><strong>function </strong>reducer(state, action) {<br>    <strong>switch </strong>(action.type) {<br>        <strong>case </strong>&#39;UPDATE_INPUT&#39;:<br>            <strong>return </strong>{<br>                inputText: action.data<br>            };<br><br><br>        <strong>default</strong>:<br>            <strong>return </strong>initialState;<br>    }<br>}</pre><p>According to react <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">documentation</a></p><blockquote>useReducer lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.</blockquote><p>First we need to import useReducer from react. So now the first line of ./src/App.js should looks like that</p><pre><strong>import </strong>React, { useReducer } <strong>from </strong>&#39;react&#39;;</pre><p>Now we need to initialize useReducer state. The simplest way is to pass the initial state as a second argument. We can do this by adding:</p><pre><strong>const </strong>[state, dispatch] = useReducer(reducer, initialState);</pre><p>And the last part in ./src/App.js is to wrap components <em>&lt;Input_one/&gt;</em> and <em>&lt;Input_two/&gt;</em> in AppContext.Provider. Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes. Providers can be nested to override values deeper within the tree.</p><p>Now ./src/App.js should looks like that:</p><pre><strong>import </strong>React, { useReducer } <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{ makeStyles } <strong>from </strong>&#39;@material-ui/core/styles&#39;;<br><br>//Material UI components<br><strong>import </strong>Container <strong>from </strong>&#39;@material-ui/core/Container&#39;;<br><strong>import </strong>Typography <strong>from </strong>&#39;@material-ui/core/Typography&#39;;<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>CssBaseline <strong>from </strong>&#39;@material-ui/core/CssBaseline&#39;;<br><strong>import </strong>Toolbar <strong>from </strong>&#39;@material-ui/core/Toolbar&#39;;<br><br>//Import our Inputs<br><strong>import </strong>Input_one <strong>from </strong>&#39;./components/Input_one&#39;;<br><strong>import </strong>Input_two <strong>from </strong>&#39;./components/Input_two&#39;;<br><br>//Styles<br><strong>const </strong>useStyles = makeStyles({<br>    toolbarTitle: {<br>        flex: 1,<br>    },<br>});<br><br>// Create context object<br><strong>export const </strong>AppContext = React.createContext();<br><br>// Set up Initial State<br><strong>const </strong>initialState = {<br><br>    inputText: &#39;&#39;,<br><br>};<br><br><strong>function </strong>reducer(state, action) {<br>    <strong>switch </strong>(action.type) {<br>        <strong>case </strong>&#39;UPDATE_INPUT&#39;:<br>            <strong>return </strong>{<br>                inputText: action.data<br>            };<br><br><br>        <strong>default</strong>:<br>            <strong>return </strong>initialState;<br>    }<br>}<br><br><strong>function </strong>App() {<br><br>  <strong>const </strong>classes = useStyles();<br><br>  <strong>const </strong>[state, dispatch] = useReducer(reducer, initialState);<br><br>  <strong>return </strong>(<br>      &lt;Container maxWidth=&quot;lg&quot;&gt;<br>          &lt;CssBaseline /&gt;<br><br>          {/*Title*/}<br>          &lt;Toolbar&gt;<br>              &lt;Typography<br>                  component=&quot;h2&quot;<br>                  variant=&quot;h5&quot;<br>                  color=&quot;inherit&quot;<br>                  align=&quot;center&quot;<br>                  noWrap<br>                  className={classes.toolbarTitle}<br>              &gt;<br>                  Pass data between react sibling components<br>              &lt;/Typography&gt;<br>          &lt;/Toolbar&gt;<br><br>          {/*Inputs*/}<br>          &lt;Grid container spacing={1}&gt;<br>              &lt;AppContext.Provider value={{ state, dispatch }}&gt;<br>                  &lt;Input_one/&gt;<br>                  &lt;Input_two/&gt;<br>              &lt;/AppContext.Provider&gt;<br>          &lt;/Grid&gt;<br><br>      &lt;/Container&gt;<br>  );<br>}<br><br><strong>export default </strong>App;</pre><p>Now we need to modify our <em>&lt;Input_one/&gt;</em> and <em>&lt;Input_two/&gt;</em> components.</p><p>All the next changes will be completely the same for both input components. First we need to import useContext from react.</p><pre><strong>import </strong>React, { useContext } <strong>from </strong>&#39;react&#39;;</pre><p>Now we need to import AppContext from App component</p><pre><strong>import </strong>{ AppContext } <strong>from </strong>&#39;../App&#39;</pre><p>To use our state values inside component we need to add</p><pre><strong>const </strong>{state, dispatch} = useContext(AppContext);</pre><p>Next add function, which will update state inputText value using dispatch. This function will be called each time, when we type something in any input.</p><pre><strong>const </strong>changeInputValue = (newValue) =&gt; {<br><br>    dispatch({ type: &#39;UPDATE_INPUT&#39;, data: newValue,});<br>};</pre><p>Now we need to set up <em>value </em>to<em> state.inputText </em>and <em>onChange</em> event should call function changeInputValue.</p><p>Now ./src/components/Input_one.js should looks like:</p><pre><strong>import </strong>React, { useContext } <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{makeStyles} <strong>from </strong>&quot;@material-ui/core/styles/index&quot;;<br><br>//Material UI components<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>Paper <strong>from </strong>&#39;@material-ui/core/Paper&#39;;<br><strong>import </strong>InputBase <strong>from </strong>&#39;@material-ui/core/InputBase&#39;;<br><br>//Material UI Icons<br><strong>import </strong>IconButton <strong>from </strong>&#39;@material-ui/core/IconButton&#39;;<br><strong>import </strong>SearchIcon <strong>from </strong>&#39;@material-ui/icons/Search&#39;;<br><br>// Import Context<br><strong>import </strong>{ AppContext } <strong>from </strong>&#39;../App&#39;<br><br><strong>const </strong>useStyles = makeStyles({<br>    root: {<br>        padding: &#39;2px 4px&#39;,<br>        display: &#39;flex&#39;,<br>        alignItems: &#39;center&#39;,<br>        width: &#39;100%&#39;,<br>    },<br>    input: {<br>        marginLeft: &#39;8px&#39;,<br>        flex: 1,<br>    },<br>    iconButton: {<br>        padding: 10,<br>    }<br>});<br><br><strong>export default function </strong>Input_one() {<br><br>    <strong>const </strong>classes = useStyles();<br><br>    <strong>const </strong>{state, dispatch} = useContext(AppContext);<br><br>    <strong>const </strong>changeInputValue = (newValue) =&gt; {<br><br>        dispatch({ type: &#39;UPDATE_INPUT&#39;, data: newValue,});<br>    };<br><br>    <strong>return</strong>(<br>        &lt;React.Fragment&gt;<br>            &lt;Grid item xs={12} md={6}&gt;<br>                &lt;Paper className={classes.root}&gt;<br>                    &lt;InputBase<br>                        className={classes.input}<br>                        placeholder=&quot;Input one&quot;<br>                        value={state.inputText}<br>                        onChange={e =&gt; changeInputValue(e.target.value)}<br>                    /&gt;<br>                    &lt;IconButton className={classes.iconButton} aria-label=&quot;search&quot;&gt;<br>                        &lt;SearchIcon /&gt;<br>                    &lt;/IconButton&gt;<br>                &lt;/Paper&gt;<br>            &lt;/Grid&gt;<br>        &lt;/React.Fragment&gt;<br>    )<br>}</pre><p>And ./src/components/Input_two.js should looks like:</p><pre><strong>import </strong>React, { useContext } <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{makeStyles} <strong>from </strong>&quot;@material-ui/core/styles/index&quot;;<br><br>//Material UI components<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>Paper <strong>from </strong>&#39;@material-ui/core/Paper&#39;;<br><strong>import </strong>InputBase <strong>from </strong>&#39;@material-ui/core/InputBase&#39;;<br><br>//Material UI Icons<br><strong>import </strong>IconButton <strong>from </strong>&#39;@material-ui/core/IconButton&#39;;<br><strong>import </strong>SearchIcon <strong>from </strong>&#39;@material-ui/icons/Search&#39;;<br><br><br>//Import Context<br><strong>import </strong>{ AppContext } <strong>from </strong>&#39;../App&#39;<br><br><strong>const </strong>useStyles = makeStyles({<br>    root: {<br>        padding: &#39;2px 4px&#39;,<br>        display: &#39;flex&#39;,<br>        alignItems: &#39;center&#39;,<br>        width: &#39;100%&#39;,<br>    },<br>    input: {<br>        marginLeft: &#39;8px&#39;,<br>        flex: 1,<br>    },<br>    iconButton: {<br>        padding: 10,<br>    }<br>});<br><br><br><strong>export default function </strong>Input_two() {<br><br>    <strong>const </strong>classes = useStyles();<br><br>    <strong>const </strong>{state, dispatch} = useContext(AppContext);<br><br>    <strong>const </strong>changeInputValue = (newValue) =&gt; {<br><br>        dispatch({ type: &#39;UPDATE_INPUT&#39;, data: newValue,});<br>    };<br><br>    <strong>return</strong>(<br>        &lt;React.Fragment&gt;<br>            &lt;Grid item xs={12} md={6}&gt;<br>                &lt;Paper className={classes.root}&gt;<br>                    &lt;InputBase<br>                        className={classes.input}<br>                        placeholder=&quot;Input two&quot;<br>                        value={state.inputText}<br>                        onChange={e =&gt; changeInputValue(e.target.value)}<br>                    /&gt;<br>                    &lt;IconButton className={classes.iconButton} aria-label=&quot;search&quot;&gt;<br>                        &lt;SearchIcon /&gt;<br>                    &lt;/IconButton&gt;<br>                &lt;/Paper&gt;<br>            &lt;/Grid&gt;<br>        &lt;/React.Fragment&gt;<br>    )<br>}</pre><p>Now, type something in any input fields and you will see that both inputs will be updated and will contain the same values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSJhj5E3dYW7tFu847ZQfg.gif" /></figure><h3>Add immutability-helper</h3><p>So now our application works how we expected. But lets update our initial state in ./src/App.js and add one more value and display it on the page. So now our initialState object should be like that:</p><pre>// Set up Initial State<br><strong>const </strong>initialState = {<br><br>    inputText: &#39;&#39;,<br>    testText: &#39;Hello world&#39;<br><br>};</pre><p>Now lets display testText on our page. Our ./src/App.js file should be like that:</p><pre><strong>import </strong>React, { useReducer } <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{ makeStyles } <strong>from </strong>&#39;@material-ui/core/styles&#39;;<br><br>//Material UI components<br><strong>import </strong>Container <strong>from </strong>&#39;@material-ui/core/Container&#39;;<br><strong>import </strong>Typography <strong>from </strong>&#39;@material-ui/core/Typography&#39;;<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>CssBaseline <strong>from </strong>&#39;@material-ui/core/CssBaseline&#39;;<br><strong>import </strong>Toolbar <strong>from </strong>&#39;@material-ui/core/Toolbar&#39;;<br><br>//Import our Inputs<br><strong>import </strong>Input_one <strong>from </strong>&#39;./components/Input_one&#39;;<br><strong>import </strong>Input_two <strong>from </strong>&#39;./components/Input_two&#39;;<br><br>//Styles<br><strong>const </strong>useStyles = makeStyles({<br>    toolbarTitle: {<br>        flex: 1,<br>    },<br>});<br><br>// Create context object<br><strong>export const </strong>AppContext = React.createContext();<br><br>// Set up Initial State<br><strong>const </strong>initialState = {<br><br>    inputText: &#39;&#39;,<br>    testText: &#39;Hello world&#39;<br><br>};<br><br><strong>function </strong>reducer(state, action) {<br>    <strong>switch </strong>(action.type) {<br>        <strong>case </strong>&#39;UPDATE_INPUT&#39;:<br>            <strong>return </strong>{<br>                inputText: action.data<br>            };<br><br><br>        <strong>default</strong>:<br>            <strong>return </strong>initialState;<br>    }<br>}<br><br><strong>function </strong>App() {<br><br>  <strong>const </strong>classes = useStyles();<br><br>  <strong>const </strong>[state, dispatch] = useReducer(reducer, initialState);<br><br>  <strong>return </strong>(<br>      &lt;Container maxWidth=&quot;lg&quot;&gt;<br>          &lt;CssBaseline /&gt;<br><br>          {/*Title*/}<br>          &lt;Toolbar&gt;<br>              &lt;Typography<br>                  component=&quot;h2&quot;<br>                  variant=&quot;h5&quot;<br>                  color=&quot;inherit&quot;<br>                  align=&quot;center&quot;<br>                  noWrap<br>                  className={classes.toolbarTitle}<br>              &gt;<br>                  Pass data between react sibling components<br>              &lt;/Typography&gt;<br>          &lt;/Toolbar&gt;<br><br>          {/*Inputs*/}<br>          &lt;Grid container spacing={1}&gt;<br>              &lt;AppContext.Provider value={{ state, dispatch }}&gt;<br>                  &lt;Input_one/&gt;<br>                  &lt;Input_two/&gt;<br>              &lt;/AppContext.Provider&gt;<br>          &lt;/Grid&gt;<br><br>          {/*display testText value*/}<br>          &lt;Toolbar&gt;<br>              &lt;Typography<br>                  component=&quot;h2&quot;<br>                  variant=&quot;h5&quot;<br>                  color=&quot;inherit&quot;<br>                  align=&quot;center&quot;<br>                  noWrap<br>                  className={classes.toolbarTitle}<br>              &gt;<br>                  {state.testText}<br>              &lt;/Typography&gt;<br>          &lt;/Toolbar&gt;<br>      &lt;/Container&gt;<br>  );<br>}<br><br><strong>export default </strong>App;</pre><p>If everything is correct, you should see now ‘Hello world` text under our inputs. Start typing something in any input. You can see what happened. Our ‘Hello word’ text disappeared.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAvCgf_BiOayIViN68GDkA.gif" /></figure><p>This happened, because currently every time you typing something in any input, you completely replacing our initialState object with just inputText new state. But there is a solution to fix that. We don’t need to replace our initialState object every time, we just need to update inputText value and not touch any other states. To make this happen, we can use <a href="https://github.com/kolodny/immutability-helper">immutability-helper</a> library, which is very well documented. Install this library by typing command in your terminal</p><pre>npm install immutability-helper --save</pre><p>Now we need just import this library in our ./src/App.js file and update reducer function according to immutability-helper documentation. So our ./src/App.js file should looks like that:</p><pre><strong>import </strong>React, { useReducer } <strong>from </strong>&#39;react&#39;;<br><strong>import </strong>{ makeStyles } <strong>from </strong>&#39;@material-ui/core/styles&#39;;<br><br>//Import immutability-helper<br><strong>import </strong>update <strong>from </strong>&#39;immutability-helper&#39;;<br><br>//Material UI components<br><strong>import </strong>Container <strong>from </strong>&#39;@material-ui/core/Container&#39;;<br><strong>import </strong>Typography <strong>from </strong>&#39;@material-ui/core/Typography&#39;;<br><strong>import </strong>Grid <strong>from </strong>&#39;@material-ui/core/Grid&#39;;<br><strong>import </strong>CssBaseline <strong>from </strong>&#39;@material-ui/core/CssBaseline&#39;;<br><strong>import </strong>Toolbar <strong>from </strong>&#39;@material-ui/core/Toolbar&#39;;<br><br>//Import our Inputs<br><strong>import </strong>Input_one <strong>from </strong>&#39;./components/Input_one&#39;;<br><strong>import </strong>Input_two <strong>from </strong>&#39;./components/Input_two&#39;;<br><br>//Styles<br><strong>const </strong>useStyles = makeStyles({<br>    toolbarTitle: {<br>        flex: 1,<br>    },<br>});<br><br>// Create context object<br><strong>export const </strong>AppContext = React.createContext();<br><br>// Set up Initial State<br><strong>const </strong>initialState = {<br><br>    inputText: &#39;&#39;,<br>    testText: &#39;Hello world&#39;<br><br>};<br><br><strong>function </strong>reducer(state, action) {<br>    <strong>switch </strong>(action.type) {<br>        <strong>case </strong>&#39;UPDATE_INPUT&#39;:<br>            <strong>return </strong>update(state, { inputText: {$set: action.data}});<br><br><br>        <strong>default</strong>:<br>            <strong>return </strong>initialState;<br>    }<br>}<br><br><strong>function </strong>App() {<br><br>  <strong>const </strong>classes = useStyles();<br><br>  <strong>const </strong>[state, dispatch] = useReducer(reducer, initialState);<br><br>  <strong>return </strong>(<br>      &lt;Container maxWidth=&quot;lg&quot;&gt;<br>          &lt;CssBaseline /&gt;<br><br>          {/*Title*/}<br>          &lt;Toolbar&gt;<br>              &lt;Typography<br>                  component=&quot;h2&quot;<br>                  variant=&quot;h5&quot;<br>                  color=&quot;inherit&quot;<br>                  align=&quot;center&quot;<br>                  noWrap<br>                  className={classes.toolbarTitle}<br>              &gt;<br>                  Pass data between react sibling components<br>              &lt;/Typography&gt;<br>          &lt;/Toolbar&gt;<br><br>          {/*Inputs*/}<br>          &lt;Grid container spacing={1}&gt;<br>              &lt;AppContext.Provider value={{ state, dispatch }}&gt;<br>                  &lt;Input_one/&gt;<br>                  &lt;Input_two/&gt;<br>              &lt;/AppContext.Provider&gt;<br>          &lt;/Grid&gt;<br><br>          {/*display testText value*/}<br>          &lt;Toolbar&gt;<br>              &lt;Typography<br>                  component=&quot;h2&quot;<br>                  variant=&quot;h5&quot;<br>                  color=&quot;inherit&quot;<br>                  align=&quot;center&quot;<br>                  noWrap<br>                  className={classes.toolbarTitle}<br>              &gt;<br>                  {state.testText}<br>              &lt;/Typography&gt;<br>          &lt;/Toolbar&gt;<br>      &lt;/Container&gt;<br>  );<br>}<br><br><strong>export default </strong>App;</pre><p>When you will do this changes, you app have to work as expected. If you type something in any input, ‘Hello world’ title should still be on the page. Now we updating just values we working with and NOT replacing all object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECWC0bprFI9ld4-RwcfqxQ.gif" /></figure><h3>Summary</h3><p>All final code of this app you can find on my <a href="https://github.com/bilousov94/sync_inputs">GitHub repo</a>. How you see, passing data between React sibling components becomes simple now. If you’re familiar with Redux, you might see a lot of familiar stuff. Context Api allows us share data that can be considered “global” for a tree of React components. This solution helps a lot for optimizing our React app, but for more complex projects with multiple nesting levels, I prefer to use <a href="https://redux.js.org/">Redux</a>. If you deal with all that process, I showed you, then you will easily understand the Redux too.</p><p>I hope that this article will help you a lot. I’m curious to know also about other interesting ways to do this. Please let me know what you think in the comments below.</p><p>🎉Happy coding🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce60f12629a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/passing-data-between-sibling-components-in-react-using-context-api-and-react-hooks-fce60f12629a">Passing data between sibling components in React using Context API and React Hooks</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>