<?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 Rebecca Oliveira on Medium]]></title>
        <description><![CDATA[Stories by Rebecca Oliveira on Medium]]></description>
        <link>https://medium.com/@RebyOliveira?source=rss-29e230b23090------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dCf8ZzpPO5VpJSkBC3vulQ.png</url>
            <title>Stories by Rebecca Oliveira on Medium</title>
            <link>https://medium.com/@RebyOliveira?source=rss-29e230b23090------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:21:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@RebyOliveira/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[Automatizando seu Github usando Shell Script]]></title>
            <link>https://medium.com/@RebyOliveira/automatizando-seu-github-usando-shell-script-76bf15d65222?source=rss-29e230b23090------2</link>
            <guid isPermaLink="false">https://medium.com/p/76bf15d65222</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[junior-developer]]></category>
            <category><![CDATA[programação]]></category>
            <category><![CDATA[shell-script]]></category>
            <dc:creator><![CDATA[Rebecca Oliveira]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 16:04:42 GMT</pubDate>
            <atom:updated>2019-02-14T15:37:47.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QWMn0DApM4jmbubKuCmNA.png" /><figcaption>Github</figcaption></figure><h4>O problema</h4><p>Alguns dias atrás eu tive um <em>&quot;probleminha&quot;</em> com a minha conta no Github… vou explicar rapidamente, para entendermos como cheguei ao Shell Script.</p><p>A minha conta do Github era um pouco antiga (não tão antiga), foi criada em uma época que eu usava para gerenciar projetos e zero códigos. Em 2018 quando comecei a estudar programação, voltei a usa-lá agora para criar meus repositórios e códigos.</p><p>Eis que semana passada resolvi formatar meu computador, tranquila de que as coisas que tinha feito estavam salvas no Github. Porém, depois do computador formatado, ao acessar o Github começou uma série de 💩:</p><ol><li>Precisava do Two Factor Authentication (Ai ai ai! Nem lembrava que isto estava ativado)</li><li>O celular que eu usava na época (2012) já não é mais o mesmo que uso em 2019 e…. claro que o 2FA do meu Github não estava no meu celular</li><li>Opa, tem o Recovery Codes, que estava a onde?! É... não sei, provavelmente ficou salvo na máquina que eu usava na antiga empresa… se perdeu né!</li><li>Abri um chamado no suporte do Github e a resposta foi &quot;Desculpa não podemos fazer nada, cancelar seu 2FA vai contra nossa política de segurança&quot;</li></ol><p>OK… minha conta do Github ficou bloqueada mesmo. Como nem tudo é tempestade, por sorte eu não tinha nenhum repositório privado — fica de lição pra você que assim como eu está começando mas tem repositórios privados, confira sempre se está tudo realmente seguro.</p><p><strong>Solução:</strong> Criar uma nova conta no Github e clonar todos os repositórios para essa nova conta.</p><p>Chamei os amigos no Twitter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*lhfyb5poH6OU8YKmqyLrHA.png" /><figcaption>Amigoossss….me ajudem!!!!</figcaption></figure><p>Graças à Nossa Senhora da Internet e das Comunidades de Programação o <a href="https://coding.com.br/">Celso Fernandes</a> me apresentou o Shell Script, e eu não precisei clonar os repositórios um a um manualmente.</p><h4>Mas afinal, o que é Shell Script?</h4><p>Shell Script é uma ferramenta de automação de instruções, que executa uma sequência de comandos.</p><blockquote>É o shell quem interpreta a linha de comando digitada pelo usuário no terminal e chama os programas desejados.</blockquote><blockquote>Como estas são as características de uma linguagem de programação, o shell é uma ferramenta muito poderosa para desenvolver scripts e programinhas rápidos para automatizar tarefas do dia-a-dia.</blockquote><p>Conheci o <a href="https://aurelio.net/shell/">blog do Aurelio</a>, ele é fera em Shell Script, <a href="https://www.shellscript.com.br/">escreveu um livro sobre esta tecnologia </a>(que eu tenho em casa — obrigada marido por ter comprado anos atrás! rsrsr) e é possível tirar muitas dúvidas sobre o assunto no site dele.</p><h4>Cirando repositórios via terminal</h4><p>Vamos começar por automatizar a criação dos repositórios.</p><p>Pelo terminal é possível criar repositórios, usando a API do Github:</p><pre>curl -u &#39;username&#39; https://api.github.com/user/repos -d &#39;{&quot;name&quot;:&quot;repository name&quot;}&#39;</pre><p>Onde &#39;username&#39; é o seu usuário do Github, e no campo o &quot;repository name&quot; inclui o nome do repositório a ser criado. Na sequencia é pedido a senha do Github e pronto, repositório criado.</p><p>Mas e se eu tiver que criar 100 repositórios? E aí que o Shell Script entra:</p><p>Todos os arquivos a seguir serão criados dentro do mesmo diretório. Vamos criar um arquivo ~/.secrets.shque salvaremos o nosso usuário e senha do Github:</p><pre>#!/bin/bash</pre><pre>export GITHUB_PASSWORD=&#39;AdventureTime&#39;</pre><pre>export GITHUB_USERNAME=&#39;Finn&#39;</pre><p>A partir daqui, vamos criar um novo documento .sh que daremos o nome decreate_repo.sh com o comando para criar um novo repositório importando o usuário e senha do nosso Github:</p><pre>#!/bin/bash curl </pre><pre>curl -u &quot;$GITHUB_USERNAME:$GITHUB_PASSWORD&quot; https://api.github.com/user/repos -d &quot;{\&quot;name\&quot;:\&quot;${1}\&quot;}&quot;</pre><p>E para criar vários repositórios usamos um outro doc .shcom o nome de create_repos.sh:</p><pre>#!/bin/bash</pre><pre>for repo in repo1 repo2 repo2<br>do<br> ./create_repo.sh $repo<br>done</pre><p>Arquivos criados, damos o comando no nosso terminal:</p><pre>$ source ~/.secrets.sh <br>$ ./create_repos.sh</pre><h4>Clonando repositórios de uma mesma conta</h4><p>Como foi o meu caso, tive que clonar todos os repositórios da minha antiga conta para a nova.</p><p>Após criar todos os novos repositórios (usei o mesmo nome para eles na minha nova conta do Github), adicionei um novo arquivo .sh com o nome de clone_repos.shpara clonar os repositórios da antiga conta.</p><pre>#!/bin/bash</pre><pre>APP_ROOT=`pwd`<br>for repo in repoA repoB repoC repoD repoE repoF</pre><pre>do<br> cd ~/src    <br> git clone https://github.com/PrincessBubblegum/${repo}.git    <br> cd ~/src/${repo}    <br> git remote rm origin    <br> git remote add origin git@github.com:Finn/${repo}.git<br> git push --set-upstream origin master<br>done<br>cd $APP_ROOT</pre><p>Na parte do código for repo in repoA repoB...é necessário colocar o nome exato do repositório o qual você está clonando, neste exemplo o nome dos repositórios seriam os criados na conta da &#39;PrincessBubblegum&#39; que o Phinn está clonando.</p><p>Arquivo criado, agora rodamos no terminal o código:</p><pre>$ ./clone_repos.sh</pre><p>E seu Github estará com todos os novos repositórios clonados, com apenas uma linha de comando no terminal.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12NUbkX6p4xOO4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12NUbkX6p4xOO4%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F12NUbkX6p4xOO4%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="398" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6d57f4067e20f622abd783ff7bfe8e2/href">https://medium.com/media/c6d57f4067e20f622abd783ff7bfe8e2/href</a></iframe><h4>Lições aprendidas</h4><p>Algumas lições aprendidas neste processo todo:</p><ol><li>Conheça a sua ferramenta de trabalho: Seu computador, seus arquivos, seu Github. Foi muito bom pra eu aprender que meu Github tinha Two Factor Authentication e eu nem sabia. Que existem chaves públicas e privadas e que salvar o Recovery Codes em um lugar seguro e acessível é muito importante.</li><li>Se você está fazendo algum trabalho repetitivo em computação, por exemplo: criando vários repositórios manualmente ou usando Crtl C + Ctrl V excessivamente, pare e pesquise porque com certeza alguém já criou um modo de automatizar.</li><li>Do not underestimate your ability, even being a beginner in programming. Research, read, ask to an experienced developers, participate in communities, this is how knowledge is built</li></ol><p>E você que chegou até aqui, usa Shell Script para automatizar algum processo? Como você costuma automatizar algumas tarefas? Compartilha com a gente aqui! :D</p><p><a href="https://medium.com/@RebyOliveira/automate-your-github-using-shell-script-570a97844dc0"><em>You can read this post in English here!</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76bf15d65222" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate your Github using Shell Script]]></title>
            <link>https://medium.com/@RebyOliveira/automate-your-github-using-shell-script-570a97844dc0?source=rss-29e230b23090------2</link>
            <guid isPermaLink="false">https://medium.com/p/570a97844dc0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[shell-script]]></category>
            <category><![CDATA[automated]]></category>
            <dc:creator><![CDATA[Rebecca Oliveira]]></dc:creator>
            <pubDate>Wed, 06 Feb 2019 16:02:54 GMT</pubDate>
            <atom:updated>2019-02-20T18:18:49.665Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating your Github using Shell Script</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QWMn0DApM4jmbubKuCmNA.png" /><figcaption>Github</figcaption></figure><h4>The problem</h4><p>A few days ago I had a “small problem” with my Github account…I’ll explain very quickly, to understanding how I discover Shell Script.</p><p>My Github account was a little bit old (not so old), was created when I used to be a project manager and zero codes. In 2018, when I started to study programming languages, I back to use, now to create my repositories and codes.</p><p>So last week I decided to format my computer, with confidence that all the things that I did were completely safe in my Github. But, after to reboot my computer, trying to access my Github, started a series of 💩:</p><ol><li>Was necessary to insert Two Factor Authentication (Ohh nooo! I didn’t remember that I had activated this 2FA)</li><li>The cellphone that I used in that time (2012) it’s not the same that I use today and… of course, I don’t have the 2FA of my Github here.</li><li>Well, there’s a Recovery Codes, and where it is? Yes…I don’t know, probably I saved in the machine that I worked in my last job… I lost!</li><li>I did contact with the support and the answer: “Sorry, there’s nothing that we can do. It’s impossible to cancel 2FA of your account, it’s our recurity rules.”</li></ol><p>Ok… my Github account was blocked. Fortunately, I had only public repositories — a lesson for you, beginner as a developer like me and had some private repositories, always check if everything is safe.</p><p><strong>Solution: </strong>To create a new Github account and to clone all repositories from my old account to this new.</p><p>So, I call my Twitter’s friends:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*lhfyb5poH6OU8YKmqyLrHA.png" /><figcaption>Frieeeennnddd…..help meeeee!</figcaption></figure><p>Thanks to Our Lady of the Internet and Programming Communities the <a href="https://coding.com.br/">Celso Fernandes</a> introduce me Shell Script, and I didn’t need to clone all repositories manually.</p><h4>But, what is a Shell Script?</h4><p>Shell Script is an instruction automation tool, which executes a sequence of commands.</p><blockquote>It is the shell that interprets the command line entered by the user on the terminal and calls the desired programs.</blockquote><blockquote>Because these are the characteristics of a programming language, shell is a very powerful tool for developing quick scripts and scripts to automate day-to-day tasks.</blockquote><p>I met the <a href="https://aurelio.net/shell/">blog of Aurelio</a>, he is really good with Shell Script, <a href="https://www.shellscript.com.br/">wrote a book about this technology</a> — in Portuguese (and I have this book at home — thanks to my husband to bought this book a few years ago…rsrsrs), is possible to solve a lot of doubts about this subject in his website.</p><h4>Creating a repository using terminal</h4><p>Let’s start to create repositories automatically.</p><p>Using terminal is possible to create a repository, using the Github API:</p><pre>curl -u &#39;username&#39; <a href="https://api.github.com/user/repos">https://api.github.com/user/repos</a> -d &#39;{&quot;name&quot;:&quot;repository name&quot;}&#39;</pre><p>Where &#39;username&#39; is your Github username, and in the field&quot;repository name&quot; is to include the name of the repository to be created. In sequence, it is necessary to fill with your Github password, and it&#39;s ready your new repository.</p><p>But, how can I do if I have to create a 100 repositories? It’s here where Sell Script starts:</p><p>All the files in this following explanation were created inside the same directory. Well, let’s create a file with the name .secrets.shthat will be saved our Github user and password.</p><pre>#!/bin/bash</pre><pre>export GITHUB_PASSWORD=&#39;AdventureTime&#39;</pre><pre>export GITHUB_USERNAME=&#39;Finn&#39;</pre><p>Here, we create a new file .sh named of create_repo.sh with the command to create a new repository, importing user and password.</p><pre>#!/bin/bash curl</pre><pre>curl -u &quot;$GITHUB_USERNAME:$GITHUB_PASSWORD&quot; <a href="https://api.github.com/user/repos">https://api.github.com/user/repos</a> -d &quot;{\&quot;name\&quot;:\&quot;${1}\&quot;}&quot;</pre><p>And to create many repositories, and use another file.sh withthe name ofcreate_repos.sh:</p><pre>#!/bin/bash</pre><pre>for repo in repo1 repo2 repo2<br>do<br> ./create_repo.sh $repo<br>done</pre><p>Files created, run in the terminal this two command lines:</p><pre>$ source ~/.secrets.sh <br>$ ./create_repos.sh</pre><h4>Cloning repositories from the same account</h4><p>In my case, I had to clone all repositories from my old account to the new one.</p><p>After to create the new repositories (I choose the same name for my new account), I add a new file clone_repos.sh to clone the repositories of my old account.</p><pre>#!/bin/bash</pre><pre>APP_ROOT=`pwd`<br>for repo in repoA repoB repoC repoD repoE repoF</pre><pre>do<br> cd ~/src    <br> git clone <a href="https://github.com/PrincessBubblegum/$%7Brepo%7D.git">https://github.com/PrincessBubblegum/${repo}.git</a>    <br> cd ~/src/${repo}    <br> git remote rm origin    <br> git remote add origin git@github.com:Finn/${repo}.git<br> git push --set-upstream origin master<br>done<br>cd $APP_ROOT</pre><p>In this part of the code for repo in repoA repoB... is necessary to insert the same name of the repositories that you are cloning, this example above, the name of the repositories will be cloned from ‘PrincessBubblegum’ account.</p><p>File create, now run in the terminal:</p><pre>$ ./clone_repos.sh</pre><p>And your Github will be with all cloned repositories, using only one line of code.</p><h4>Lessons learned</h4><p>Some lessons that I learned in this process:</p><ol><li>You have to understand your work tools: The computer, the files, your Github. Was good for me to know that I had Two Factor Authentication in my Github account that I had never imagined before. And it exists public and private keys, and to save Recovery Codes in a safe place is very important.</li><li>If you are doing some repetitive job in computing, for example: creating many repositories manually, or using a lot Crtl C + Ctrl V, stop and do research, because for sure someone created a way to automate this process.</li><li>Não subestime sua capacidade, mesmo sendo iniciante em programação. Pesquise, leia, pergunte para desenvolvedores experientes, participe de comunidades, é assim que se constrói conhecimento.</li></ol><p>And you who read until here, do you use Shell Script to automate something? How do you usually automate your tasks? Share with us here. :D</p><p><a href="https://medium.com/@RebyOliveira/automatizando-seu-github-usando-shell-script-76bf15d65222"><em>Você pode ler este artigo em Português aqui!</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=570a97844dc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use(and test) React Router with screen resize]]></title>
            <link>https://medium.com/@RebyOliveira/how-to-use-and-test-react-router-with-screen-resize-52f1e6bcc562?source=rss-29e230b23090------2</link>
            <guid isPermaLink="false">https://medium.com/p/52f1e6bcc562</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Rebecca Oliveira]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 18:34:57 GMT</pubDate>
            <atom:updated>2019-01-17T13:33:45.757Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use (and test) React Router with screen resize</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQ4DfO9iKpq39YyGLfnE-A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/vWfKaO0k9pc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ryoji Iwata</a> on <a href="https://unsplash.com/search/photos/street?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When I started to study and learn React, I met React Router and how this library can help us inside a web application.</p><p>I was developing a web app, thinking in mobile first, where during the screen resize, an action button should be changed together with the URL link.</p><p>Before to include this in my application, I created a React App to validate my idea, to test only this behavior. Let’s check it out.</p><h4>Creating a new React App</h4><p>The first step is to create a new React App to play. I highly recommend when you’re developing something and find some particular challenge where you haven’t sure how to do, to start a separated react app and to try different experiments until finding a good solution for your project.</p><p>It’s pretty easy to validate and test a solution in a separate way.</p><p>To create a new React App, follow the steps on <a href="https://reactjs.org/">official documentation</a>.</p><pre>npx create-react-app test-router-sreen<br>cd test-router-sreen<br>npm start / yarn start</pre><p>Let’s start creating a simple JSX, in our “app” will be organized with only three components: Device / Mobile / App, this last one is our Index.</p><p>In my test app, I used Material UI (<a href="https://material-ui.com/">get started here</a>), because it’s a library that’s I love to work, but you can use the only HTML and insert CSS if you want.</p><h4>The app test</h4><p>The idea of this app is to have a screen with a button ‘Show Mobile’, and when the user does the action ‘click’ on this button, a component is rendered with a message: ‘ I am rendered only on mobile’, and when moving the screen size, the button change for ‘Show Device’, then click on the button, shows a message ‘I am rendered only on device’.</p><pre>//App</pre><pre>import React, { Component } from &#39;react&#39;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;<br>import Hidden from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Hidden&#39;</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>     &lt;div className=&quot;App&quot;&gt;<br>      &lt;Hidden xsDown&gt;<br>       &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>         Show Device<br>       &lt;/Button&gt;<br>       &lt;/Hidden&gt; <br>       &lt;Hidden smUp&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>          Show Mobile<br>        &lt;/Button&gt;<br>       &lt;/Hidden&gt;<br>      &lt;/div&gt;<br>     ); <br>    }<br>   }</pre><pre>export default App;</pre><p>I applied the Hidden of Material UI for the button show / hidden at the breakpoints.</p><p>The components Device and Mobile was created very simple.</p><pre>//Device//</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;;<br>import Typography from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Typography&#39;;</pre><pre>class Device extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;Typography component=&quot;h2&quot; variant=&quot;h1&quot; gutterBottom&gt;<br>          I am rendered only on Device :)<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Device;</pre><pre>//Mobile//</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;;<br>import Typography from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Typography&#39;;</pre><pre>class Mobile extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;Typography component=&quot;h2&quot; variant=&quot;h1&quot; gutterBottom&gt;<br>          I am rendered only on Mobile :)<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Mobile;</pre><h4>Starting React Router</h4><p>The challenge now is:</p><ol><li>Tho show the component Mobile when to click on ‘Mobile’ button, or to show the component Device when clicking on button ‘Device,’ changing the URL to <em>/mobile</em> ou <em>/device</em>.</li><li>Moving the screen size with the component rendered, the route needs to change between /mobile’ to index ‘/’ or /device’ to index ‘/’, automatically.</li></ol><p>To use React Router in our project, we use the instructions<a href="https://reacttraining.com/react-router/web/guides/quick-start"> on the documentation</a> to install the package.</p><pre>npm install react-router-dom</pre><pre>or</pre><pre>yarn add react-router-dom</pre><p>First of all, let’s create the route inside the buttons Mobile and Device. We can’t forget to import the dependencies.</p><pre>//App</pre><pre>...<br>import <br>{ BrowserRouter as Router, <br>Route, <br>Link } from &quot;react-router-dom&quot;<br>import Mobile from &#39;./Mobile&#39;<br>import Device from &#39;./Device&#39;</pre><p>And include the Route at the code with Link on the buttons.</p><pre><em>class App extends Component {<br>  render() {<br>    return (<br>   </em> <strong> &lt;Router&gt;</strong><em><br>      &lt;div className=&quot;App&quot;&gt;<br>      &lt;Hidden xsDown&gt;<br>       </em><strong>&lt;Link to=&#39;/mobile&#39;&gt;<br></strong><em>        &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>          Show Device<br>        &lt;/Button&gt;<br>       </em><strong>&lt;/Link&gt;<br>      </strong><em>&lt;/Hidden&gt; <br>      &lt;Hidden smUp&gt;<br></em><strong><em>       </em>&lt;Link to=&#39;/mobile&#39;&gt;</strong><br>        <em>&lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>          Show Mobile<br>        &lt;/Button&gt;<br></em><strong><em>       </em>&lt;/Link&gt;</strong><br>     <em>&lt;/Hidden&gt;</em><br>     &lt;<strong>Route path=&quot;/device&quot; component={Device} /&gt;<br>     &lt;Route path=&quot;/mobile&quot; component={Mobile} /&gt;</strong><br><em>    &lt;/div&gt;<br></em><strong>   &lt;/Router&gt;</strong><em><br>  ); <br> }<br>}</em></pre><pre><em>export default App;</em></pre><p>Alright, the route for components is linked on the button, when we click on render the component and change the path, but an important point is missing now. During the screen resize, change the route but isn’t show the actual component.</p><p>To see the resize event on the screen, and dispatch an action, e use a package <a href="https://www.npmjs.com/package/react-resize-detector">React Resize Detector</a>.</p><p>Installing…</p><pre>npm i react-resize-detector<br>// or<br>yarn add react-resize-detector</pre><p>On the documentation of this package, is possible to see that we can apply using different forms, as Callback Pattern, Child Function Pattern, Child Component Pattern…etc. Is Child Component Pattern to know the exact point where the resize should apply the Redirect and change the URL route.</p><p>Adding the Redirect on imports of react-router-dom and React Resize Detector.</p><pre>//App</pre><pre>...<br>import <br>{ BrowserRouter as Router, <br>Route, <br>Link,<br><strong>Redirect </strong>} from &quot;react-router-dom&quot;<br><strong>import ReactResizeDetector from &#39;react-resize-detector&#39;<br>...</strong></pre><p>First, we include the&lt;ReactResizeDetector /&gt; inside the DOM tree, and we verify the breakpoint of Material UI for mobile, where the button change from Device to Mobile is smaller than <em>width</em> 600 px.</p><p>Using this information, add a constant, with a rule of resizing, using ternary operator and Redirect do Router to change the route according to <em>with </em>of<em> </em>the screen size. We created a function CheckIfRedirect.</p><pre>const CheckIfRedirect = ({width, height}) =&gt; {<br>  const path = window.location.pathname<br>  console.log(&#39;resize&#39;, width, height, path)</pre><pre>if ((width &lt; 600 &amp;&amp; path === &quot;/device&quot;) || (width &gt;= 600 &amp;&amp; path === &quot;/mobile&quot;)) {<br>    return &lt;Redirect to={{pathname: &quot;/&quot;}} /&gt;<br>  } else {<br>    return &lt;&gt;&lt;/&gt;<br>  }<br>}</pre><p>With this rule, it’s specific when the width is smaller than 600 px and the path <strong>‘/device’ </strong>or <em>with </em>bigger or equal 600 px and the path <strong>‘/mobile’ </strong>then to redirect to pathname:<strong> ‘/’ </strong>in this case, is our Index without a specific component.</p><p>The information window.location.pathnameis possible to find inspecting the console of the browser.</p><p>So, separating the code inside the function App in another function, we called Body.</p><pre>const Body = () =&gt; (<br>  &lt;div className=&quot;App&quot;&gt;<br>    &lt;Hidden xsDown&gt;<br>      &lt;Link to=&#39;/device&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>            Show Device<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Hidden smUp&gt;<br>      &lt;Link to=&#39;/mobile&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>            Show Mobile<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Route path=&quot;/device&quot; component={H1Device} /&gt;<br>    &lt;Route path=&quot;/mobile&quot; component={H1Mobile} /&gt;<br>  &lt;/div&gt;<br>)</pre><p>To organize our code, inside the App we will include the Router only on Body, theReactResizeDetector and this new function of CheckIfRedirect.</p><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;&gt;<br>          &lt;Body /&gt;<br>          &lt;ReactResizeDetector handleWidth handleHeight&gt;<br>            &lt;CheckIfRedirect /&gt;<br>          &lt;/ReactResizeDetector&gt;<br>        &lt;/&gt;<br>      &lt;/Router&gt;<br>    );<br>  }<br>}</pre><p>In the end, the complete code of our application:</p><pre>import React, { Component } from &#39;react&#39;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;<br>import Hidden from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Hidden&#39;<br>import { BrowserRouter as Router, Route, Link, Redirect } from &quot;react-router-dom&quot;<br>import Mobile from &#39;./Mobile&#39;<br>import Device from &#39;./Device&#39;<br>import ReactResizeDetector from &#39;react-resize-detector&#39;</pre><pre><strong>const Body</strong> = () =&gt; (<br>  &lt;div className=&quot;App&quot;&gt;<br>    &lt;Hidden xsDown&gt;<br>      &lt;Link to=&#39;/device&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>            Show Device<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Hidden smUp&gt;<br>      &lt;Link to=&#39;/mobile&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>            Show Mobile<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Route path=&quot;/device&quot; component={H1Device} /&gt;<br>    &lt;Route path=&quot;/mobile&quot; component={H1Mobile} /&gt;<br>  &lt;/div&gt;<br>)</pre><pre><strong>const CheckIfRedirect</strong> = ({width, height}) =&gt; {<br>  const path = window.location.pathname</pre><pre>console.log(&#39;resize&#39;, width, height, path)</pre><pre>if ((width &lt; 600 &amp;&amp; path === &quot;/device&quot;) || (width &gt;= 600 &amp;&amp; path === &quot;/mobile&quot;)) {<br>    return &lt;Redirect to={{pathname: &quot;/&quot;}} /&gt;<br>  } else {<br>    return &lt;&gt;&lt;/&gt;<br>  }<br>}</pre><pre><strong>class App extends Component</strong> {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;&gt;<br>          &lt;Body /&gt;<br>          &lt;ReactResizeDetector handleWidth handleHeight&gt;<br>            &lt;CheckIfRedirect /&gt;<br>          &lt;/ReactResizeDetector&gt;<br>        &lt;/&gt;<br>      &lt;/Router&gt;<br>    );<br>  }<br>}</pre><pre>export default App;</pre><h4>Final result</h4><p>In the image below, it is possible to see the button changing from <em>Device</em> to <em>Mobile</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0rrW7u4lG34s4VEvDrgQg.gif" /></figure><p>And clicking on the button, the change of the path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_93JyH8g53g_auZJJEKiw.gif" /></figure><h4>Testing our application</h4><p>To write a test is essential, to certify that things are working as expected.</p><p>I found information about how to test this application on the documentation of <a href="https://react-testing-examples.com/jest-rtl/react-router/">React-Testing-Examples</a>. Another library that helps me a lot was the <a href="https://testing-library.com/">DOM Testing Library</a>.</p><p>Instaling…</p><pre>npm install react-testing-library</pre><pre>or</pre><pre>yarn add react-testing-library</pre><p>To check that’s everything it’s going well, let’s start to create a test to render the main component.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br>import { render, waitForElement } from &#39;react-testing-library&#39;</pre><pre>const renderComponent = () =&gt; (<br>  render(<br>    &lt;App /&gt;<br>  )<br>)</pre><pre>test(&#39;renders without crashing&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</pre><pre>await waitForElement(() =&gt; getByText(&#39;Show Device&#39;));<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*V7uz4SPJbcr2U43yCS6fcA.png" /><figcaption>In the terminal, running the test, it’s working.</figcaption></figure><p>Now, testing the event to click on the button and render the message that the browser is on device size.</p><p>To simulate the click, we add the fireEvent, passing the message that should be rendered as a string.</p><pre>...<br>import { render, waitForElement, <strong>fireEvent</strong> } from &#39;react-testing-library&#39;</pre><pre>...</pre><pre>test(&#39;click on show device&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</pre><pre>fireEvent.click(getByText(&#39;Show Device&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on Device:)&#39;));</pre><pre>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*0gv35ptOzz4ZnzA9dBkX_w.png" /><figcaption>The test still ok, cool :)</figcaption></figure><p>Now start a delicate part of our test, to simulate the screen resize, changing the button for <em>mobile.</em></p><p>For this, we include a function, using global.innerWidth as a standard size for a device (1024 px), and adding global.dispachEvent to dispatch a new &#39;resize&#39; event.</p><p>The test to render the component and the click simulation is the same as before, for <em>device</em>, including only a new size for the screen.</p><pre>...</pre><pre><strong>afterEach(() =&gt; {<br>  global.innerWidth = 1024<br>  global.dispatchEvent(new Event(&#39;resize&#39;))<br>});</strong></pre><pre>test(&#39;click on show device&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</pre><pre>fireEvent.click(getByText(&#39;Show Device&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on Device:)&#39;));<br>});</pre><pre><strong>test(&#39;click on show mobile&#39;, async () =&gt; {</strong><br>  <em>// Change the viewport to 500px.</em><br> <strong> global.innerWidth = 500;</strong></pre><pre><em>// Trigger the window resize event.</em><br>  <strong>global.dispatchEvent(new Event(&#39;resize&#39;));</strong></pre><pre><strong>const { getByText } = renderComponent();<br>  fireEvent.click(getByText(&#39;Show Mobile&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on mobile ;)&#39;));<br>});</strong></pre><pre><strong>test(&#39;resize to mobile&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</strong><br><em>  // Change the viewport to 500px.</em><br> <strong> global.innerWidth = 500;</strong></pre><pre><em>// Trigger the window resize event.</em><br>  g<strong>lobal.dispatchEvent(new Event(&#39;resize&#39;));</strong></pre><pre><em>// wait react component render after event dispatch</em><br>  <strong>await waitForElement(() =&gt; getByText(&#39;Show Mobile&#39;));<br>  fireEvent.click(getByText(&#39;Show Mobile&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on mobile ;)&#39;));<br>});</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Ov_pDMSnqljik62Qyo6NZQ.png" /><figcaption>All test passed. The application it’s working as expected.</figcaption></figure><h4>In the end…</h4><p>This is one solution to use React Router and change the path according to the screen resize, useful in an app where is necessary to change the route and component rendered, changing from mobile to device (or vice-versa)</p><p>I know that exist other ways to get the same final result using different tools. And you, how to develop your code to create something like this? For me, it is nice to receive different opinions and technical experiences to share knowledge. :)</p><p>You can read this post in <a href="https://medium.com/@RebyOliveira/como-aplicar-e-testar-react-router-para-alern%C3%A2ncia-de-rota-ao-redimensionar-uma-tela-bb203f45727"><em>Portuguese</em> here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52f1e6bcc562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como aplicar (e testar) React Router para alernância de rota ao redimensionar uma tela]]></title>
            <link>https://medium.com/@RebyOliveira/como-aplicar-e-testar-react-router-para-alern%C3%A2ncia-de-rota-ao-redimensionar-uma-tela-bb203f45727?source=rss-29e230b23090------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb203f45727</guid>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rebecca Oliveira]]></dc:creator>
            <pubDate>Wed, 16 Jan 2019 16:58:17 GMT</pubDate>
            <atom:updated>2019-01-18T09:55:00.727Z</atom:updated>
            <content:encoded><![CDATA[<h3>Como aplicar (e testar) React Router para alternância de rota ao redimensionar uma tela</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQ4DfO9iKpq39YyGLfnE-A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/vWfKaO0k9pc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ryoji Iwata</a> on <a href="https://unsplash.com/search/photos/street?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Logo que comecei a estudar e me dedicar em React, conheci React Router e como ele pode nos ajudar dentro de uma aplicação web.</p><p>Estava desenvolvendo um sistema web, pensando em mobile first, me deparei com uma situação, onde ao dar um resize na tela, um botão de ação deveria ser alterado assim como a rota na URL.</p><p>Antes de incluir isto na minha aplicação, criei um React app para validar a ideia, para testar exclusivamente essa mudança de botão e rota. Na sequencia explico o passo a passo.</p><h4>Criando um novo React App</h4><p>Um primeiro passo é criar um React app para brincar. Recomendo muito sempre que estiverem desenvolvendo algo e se deparar com um dúvida pontual, criem um app separado para fazer vários experimentos até encontrar uma solução mais cabível ao seu projeto.</p><p>É mais fácil validar a solução e testar, de forma isolada.</p><p>Para criar um React app basta seguir os passos explicados na <a href="https://reactjs.org/">documentação oficial.</a></p><pre>npx create-react-app test-router-sreen<br>cd test-router-sreen<br>npm start / yarn start</pre><p>Vamos começar criando um simples JSX, nosso “app” terá apenas 3 componentes: Device / Mobile / App sendo este último a nossa Index.</p><p>Na minha aplicação teste usei Material UI (<a href="https://material-ui.com/">get started here</a>), pois é uma biblioteca que eu gosto muito de trabalhar, mas você pode usar somente HTML e incluir algum CSS se assim desejar. :)</p><h4>O app teste</h4><p>A ideia era ter uma tela com um botão ‘Show Mobile’, que ao clicar, montasse uma componente com a mensagem: ‘ I am rendered only on mobile’, e conforme fosse aumentando o screen size, o botão alterasse para ‘Show Device’, e ao clicar aparecesse a mensagem ‘I am rendered only on device’.</p><pre>//App</pre><pre>import React, { Component } from &#39;react&#39;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;<br>import Hidden from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Hidden&#39;</pre><pre>class App extends Component {<br>  render() {<br>    return (<br>     &lt;div className=&quot;App&quot;&gt;<br>      &lt;Hidden xsDown&gt;<br>       &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>         Show Device<br>       &lt;/Button&gt;<br>       &lt;/Hidden&gt; <br>       &lt;Hidden smUp&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>          Show Mobile<br>        &lt;/Button&gt;<br>       &lt;/Hidden&gt;<br>      &lt;/div&gt;<br>     ); <br>    }<br>   }</pre><pre>export default App;</pre><p>Usei o Hidden do Material UI para o botão aparecer / desaparecer nos break points.</p><p>Já as componentes Device e Mobile ficaram extremamente simples.</p><pre>//Device//</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;;<br>import Typography from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Typography&#39;;</pre><pre>class Device extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;Typography component=&quot;h2&quot; variant=&quot;h1&quot; gutterBottom&gt;<br>          I am rendered only on Device :)<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Device;</pre><pre>//Mobile//</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;;<br>import Typography from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Typography&#39;;</pre><pre>class Mobile extends Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;Typography component=&quot;h2&quot; variant=&quot;h1&quot; gutterBottom&gt;<br>          I am rendered only on Mobile :)<br>        &lt;/Typography&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Mobile;</pre><h4>Iniciando o React Router</h4><p>O desafio agora ficou em :</p><ol><li>Montar a componente Mobile quando clicar no botão ‘Mobile’, ou montar a componente Device quando clicar no botão ‘Device’, alternando o path da url para /mobile’ ou /device’.</li><li>Ao movimentar a tela, com a componente renderizada e efetuar o resize, a rota deve alterar entre /mobile’ para index ‘/’ ou /device’ para index ‘/’, automaticamente.</li></ol><p>Para usar o React Router no nosso projeto seguimos as <a href="https://reacttraining.com/react-router/web/guides/quick-start">instruções da documentação</a> para a instalação do pacote.</p><pre>npm install react-router-dom </pre><pre>ou</pre><pre>yarn add react-router-dom</pre><p>Primeiramente vamos criar a rota nos botões de Mobile e Device. Não podemos esquecer de dar um ‘import’ nas dependências.</p><pre>//App</pre><pre>...<br>import <br>{ BrowserRouter as Router, <br>Route, <br>Link } from &quot;react-router-dom&quot;<br>import Mobile from &#39;./Mobile&#39;<br>import Device from &#39;./Device&#39;</pre><p>E incluir o Route no código com Link nos botões.</p><pre><em>class App extends Component {<br>  render() {<br>    return (<br>   </em> <strong> &lt;Router&gt;</strong><em><br>      &lt;div className=&quot;App&quot;&gt;<br>      &lt;Hidden xsDown&gt;<br>       </em><strong>&lt;Link to=&#39;/mobile&#39;&gt;<br></strong><em>        &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>          Show Device<br>        &lt;/Button&gt;<br>       </em><strong>&lt;/Link&gt;<br>      </strong><em>&lt;/Hidden&gt; <br>      &lt;Hidden smUp&gt;<br></em><strong><em>       </em>&lt;Link to=&#39;/mobile&#39;&gt;</strong><br>        <em>&lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>          Show Mobile<br>        &lt;/Button&gt;<br></em><strong><em>       </em>&lt;/Link&gt;</strong><br>     <em>&lt;/Hidden&gt;</em><br>     &lt;<strong>Route path=&quot;/device&quot; component={Device} /&gt;<br>     &lt;Route path=&quot;/mobile&quot; component={Mobile} /&gt;</strong><br><em>    &lt;/div&gt;<br></em><strong>   &lt;/Router&gt;</strong><em><br>  ); <br> }<br>}</em></pre><pre><em>export default App;</em></pre><p>Certo, a rota para as componentes está linkada no botão, quando clicamos aparece a componente na tela e muda a rota, mas falta um ponto que é o mais importante nesse momento. Ao dar o resize, alterar a rota e não renderizar a componente atual, mas sim outra ao clicar no botão com novo screen size.</p><p>Para escutar o evento de resize da tela e disparar uma ação, usamos um pacote chamado <a href="https://www.npmjs.com/package/react-resize-detector">React Resize Detector</a>.</p><p>Instalando…</p><pre>npm i react-resize-detector</pre><pre>ou</pre><pre>yarn add react-resize-detector</pre><p>Na documentação é possível ver que pode ser aplicado de diversas formas, como Callback Pattern, Child Function Pattern, Child Component Pattern…etc. É com Child Component Pattern que iremos setar o exato ponto onde o resize deverá aplicar o Redirect e mudar a rota da URL.</p><p>Adicionamos o Redirect nos imports do react-router-dom e o React Resize Detector.</p><pre>//App</pre><pre>...<br>import <br>{ BrowserRouter as Router, <br>Route, <br>Link,<br><strong>Redirect </strong>} from &quot;react-router-dom&quot;<br><strong>import ReactResizeDetector from &#39;react-resize-detector&#39;<br>...</strong></pre><p>Primeiro incluímos o &lt;ReactResizeDetector /&gt; dentro da árvore o DOM do App, e verificamos que o ponto do break point do Material UI para mobile, onde o botão muda de Device para Mobile é menor que <em>width</em> 600 px.</p><p>Com base nessa informação, adicionar uma constante, com uma regra de resize utilizando operador ternário e Redirect do Router para mudar a rota de acordo com o tamanho da tela. Criamos a função CheckIfRedirect.</p><pre>const CheckIfRedirect = ({width, height}) =&gt; {<br>  const path = window.location.pathname<br>  console.log(&#39;resize&#39;, width, height, path)</pre><pre> if ((width &lt; 600 &amp;&amp; path === &quot;/device&quot;) || (width &gt;= 600 &amp;&amp; path === &quot;/mobile&quot;)) {<br>    return &lt;Redirect to={{pathname: &quot;/&quot;}} /&gt;<br>  } else {<br>    return &lt;&gt;&lt;/&gt;<br>  }<br>}</pre><p>Com essa regra deixamos claro que quando o width for menor que 600px e o path <strong>‘/device’</strong> ou <em>with</em> for maior ou igual que 600px e o path<strong> ‘/mobile’</strong>, então redireciona para pathname:<strong> ‘/’</strong> que no caso é a nossa index sem nenhuma componente renderizada.</p><p>A informação de window.location.pathnameencontramos ao inspecionar o console do navegador.</p><p>Separamos então todo o código que estava até então dentro da função App e separamos em uma nova função, que daremos o nome de Body.</p><pre>const Body = () =&gt; (<br>  &lt;div className=&quot;App&quot;&gt;<br>    &lt;Hidden xsDown&gt;<br>      &lt;Link to=&#39;/device&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>            Show Device<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Hidden smUp&gt;<br>      &lt;Link to=&#39;/mobile&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>            Show Mobile<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Route path=&quot;/device&quot; component={H1Device} /&gt;<br>    &lt;Route path=&quot;/mobile&quot; component={H1Mobile} /&gt;<br>  &lt;/div&gt;<br>)</pre><p>Para o nosso código ficar mais organizados, dentro do App vamos colocar apenas o Router com o Body , o ReactResizeDetector e essa nova função do CheckIfRedirect.</p><pre>class App extends Component {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;&gt;<br>          &lt;Body /&gt;<br>          &lt;ReactResizeDetector handleWidth handleHeight&gt;<br>            &lt;CheckIfRedirect /&gt;<br>          &lt;/ReactResizeDetector&gt;<br>        &lt;/&gt;<br>      &lt;/Router&gt;<br>    );<br>  }<br>}</pre><p>Ao final, o código da nossa aplicação ficou assim.</p><pre>import React, { Component } from &#39;react&#39;<br>import Button from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Button&#39;<br>import Hidden from &#39;<a href="http://twitter.com/material">@material</a>-ui/core/Hidden&#39;<br>import { BrowserRouter as Router, Route, Link, Redirect } from &quot;react-router-dom&quot;<br>import Mobile from &#39;./Mobile&#39;<br>import Device from &#39;./Device&#39;<br>import ReactResizeDetector from &#39;react-resize-detector&#39;</pre><pre><strong>const Body</strong> = () =&gt; (<br>  &lt;div className=&quot;App&quot;&gt;<br>    &lt;Hidden xsDown&gt;<br>      &lt;Link to=&#39;/device&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>            Show Device<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Hidden smUp&gt;<br>      &lt;Link to=&#39;/mobile&#39;&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;secondary&quot;&gt;<br>            Show Mobile<br>        &lt;/Button&gt;<br>      &lt;/Link&gt;<br>    &lt;/Hidden&gt;<br>    &lt;Route path=&quot;/device&quot; component={H1Device} /&gt;<br>    &lt;Route path=&quot;/mobile&quot; component={H1Mobile} /&gt;<br>  &lt;/div&gt;<br>)</pre><pre><strong>const CheckIfRedirect</strong> = ({width, height}) =&gt; {<br>  const path = window.location.pathname</pre><pre> console.log(&#39;resize&#39;, width, height, path)</pre><pre> if ((width &lt; 600 &amp;&amp; path === &quot;/device&quot;) || (width &gt;= 600 &amp;&amp; path === &quot;/mobile&quot;)) {<br>    return &lt;Redirect to={{pathname: &quot;/&quot;}} /&gt;<br>  } else {<br>    return &lt;&gt;&lt;/&gt;<br>  }<br>}</pre><pre><strong>class App extends Component</strong> {<br>  render() {<br>    return (<br>      &lt;Router&gt;<br>        &lt;&gt;<br>          &lt;Body /&gt;<br>          &lt;ReactResizeDetector handleWidth handleHeight&gt;<br>            &lt;CheckIfRedirect /&gt;<br>          &lt;/ReactResizeDetector&gt;<br>        &lt;/&gt;<br>      &lt;/Router&gt;<br>    );<br>  }<br>}</pre><pre>export default App;</pre><h4>Resultado final</h4><p>Abaixo podemos ver o botão alterando de <em>Device</em> para <em>Mobile.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0rrW7u4lG34s4VEvDrgQg.gif" /></figure><p>E ao clicar o botão, a mudança de rota.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_93JyH8g53g_auZJJEKiw.gif" /></figure><h4>Testando nossa aplicação</h4><p>Tão importante quanto escrever um código é testa-lo.</p><p>Busquei informações de como escrever um teste para esta aplicação na documentação do <a href="https://react-testing-examples.com/jest-rtl/react-router/">React-Testing-Examples</a>. Outra biblioteca que me ajudou muito também foi a <a href="https://testing-library.com/">DOM Testing Library</a>.</p><p>Instalando…</p><pre>npm install react-testing-library</pre><pre>ou</pre><pre>yarn add react-testing-library</pre><p>Para certificarmos de que está funcionando de acordo com o que queremos, vamos começar escrevendo um teste que renderiza a componente inteira.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br>import { render, waitForElement } from &#39;react-testing-library&#39;</pre><pre>const renderComponent = () =&gt; (<br>  render(<br>    &lt;App /&gt;<br>  )<br>)</pre><pre>test(&#39;renders without crashing&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</pre><pre>await waitForElement(() =&gt; getByText(&#39;Show Device&#39;));<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*V7uz4SPJbcr2U43yCS6fcA.png" /><figcaption>No terminal, ao rodar o teste a confirmação.</figcaption></figure><p>Agora vamos testar o evento de clicar no botão e renderizar a mensagem de que o navegador está no tamanho para <em>device.</em></p><p>Para simularmos o click, adicionamos o fireEvent, passando a mensagem que deverá ser renderizada como uma string.</p><pre>...<br>import { render, waitForElement, <strong>fireEvent</strong> } from &#39;react-testing-library&#39;</pre><pre>...</pre><pre>test(&#39;click on show device&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</pre><pre>fireEvent.click(getByText(&#39;Show Device&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on Device:)&#39;));</pre><pre>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*0gv35ptOzz4ZnzA9dBkX_w.png" /><figcaption>Teste continua passando, legal :)</figcaption></figure><p>Agora entramos em uma parte um pouco mais delicada para o teste, simular o redimensionamento da tela, alterando o botão para <em>mobile.</em></p><p>Para isso, vamos incluir uma função, utilizando global.innerWidth com tamanho padrão de device (1024 px), e adicionando global.dispachEvent um para um novo evento &#39;resize&#39;.</p><p>Vejam que o teste para renderizar a componente e a simulação do click no botão é igual a anterior, para o <em>device, </em>incluímos apenas um novo tamanho de tela.</p><pre>...</pre><pre><strong>afterEach(() =&gt; {<br>  global.innerWidth = 1024<br>  global.dispatchEvent(new Event(&#39;resize&#39;))<br>});</strong></pre><pre>test(&#39;click on show device&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</pre><pre>fireEvent.click(getByText(&#39;Show Device&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on Device:)&#39;));<br>});</pre><pre><strong>test(&#39;click on show mobile&#39;, async () =&gt; {</strong><br>  <em>// Change the viewport to 500px.</em><br> <strong> global.innerWidth = 500;</strong></pre><pre><em>// Trigger the window resize event.</em><br>  <strong>global.dispatchEvent(new Event(&#39;resize&#39;));</strong></pre><pre><strong>const { getByText } = renderComponent();<br>  fireEvent.click(getByText(&#39;Show Mobile&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on mobile ;)&#39;));<br>});</strong></pre><pre><strong>test(&#39;resize to mobile&#39;, async () =&gt; {<br>  const { getByText } = renderComponent();</strong><br><em>  // Change the viewport to 500px.</em><br> <strong> global.innerWidth = 500;</strong></pre><pre><em>// Trigger the window resize event.</em><br>  g<strong>lobal.dispatchEvent(new Event(&#39;resize&#39;));</strong></pre><pre><em>// wait react component render after event dispatch</em><br>  <strong>await waitForElement(() =&gt; getByText(&#39;Show Mobile&#39;));<br>  fireEvent.click(getByText(&#39;Show Mobile&#39;));<br>  await waitForElement(() =&gt; getByText(&#39;I am rendered only on mobile ;)&#39;));<br>});</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*Ov_pDMSnqljik62Qyo6NZQ.png" /><figcaption>Todos os teste passaram. Aplicação funcionando como esperado.</figcaption></figure><h4>Observações finais</h4><p>Esta é uma forma de utilizar React Router e mudar a rota de acordo com redimensionamento da tela, sendo muito útil em um sistema que precisa alterar a rota e a componente quando passar de mobile para device (ou vice e versa).</p><p>Sabemos que existe outras meios de obter o mesmo resultado utilizando diferentes ferramentas. E você, como desenvolveria seu código para obter um resultado semelhante? Gosto de ter mais opiniões e experiências técnicas para compartilharmos conhecimentos. :)</p><p>Você pode ler este post em <a href="https://medium.com/@RebyOliveira/how-to-use-and-test-react-router-with-screen-resize-52f1e6bcc562"><em>Inglês</em> aqui.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb203f45727" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I decided to become a web developer]]></title>
            <link>https://medium.com/@RebyOliveira/why-i-decided-to-become-a-web-developer-3d82d301cd4d?source=rss-29e230b23090------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d82d301cd4d</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[career-change]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Rebecca Oliveira]]></dc:creator>
            <pubDate>Tue, 11 Sep 2018 13:20:35 GMT</pubDate>
            <atom:updated>2018-12-27T15:22:07.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*krJsZsRUsIz3kCEW8VaC0A.gif" /></figure><p>My story started when I was 5 years old…zzzzz…I’m kidding! But summing up, for a long period in my life, I felt that I was in a wrong way.</p><p>All my career until here was into the business area. My background was in business. But the more I delved into this area, the more I felt I was not happy investing my time in this working field.</p><p>During some years, I worked in a small startup as a business/financial coordinator and project manager. My responsibility, with a small IT team, was to create the main idea of each project, draw the screens, how the software should work for the developers to build the software. Sometimes worked, I loved to see how funny was to write a lot of codes and…tcharaaaammmm…. something appears on computer/mobile screen. But sometimes…doesn’t worked good. I was thinking that I should learn how to code, maybe was possible to help better our developers team, and to have this feeling to see things been build.</p><p>At the end of 2016, the CEO of this company decided to stop operations, keeping just current customers, shutting down the contracts with all employees, included me.</p><p>I decided that 2017 should be as a sabbatical year for me. I needed that time to organize my mind, my feeling and take the best decisions for my future professional life.</p><p>With the help of my husband, I created a simple table, listing what I would like to do starting now, how I see me in the future and what is my plan B if I had some wrong decision.</p><p>I prioritized in that list the liberty. I would like to work with something were I could use my creativity, to have mobility (to work remotely if necessary), to stay in contact with people more experience to help me to increase my knowledge, to have proper compensation, to see what I did and to remain happy to be evolving and doing something with love.</p><p>So, here I am! I gave me a break in my business life to start to code. All knowledge that I acquired before is a very, very important part of who I am. Today I feel that with all business background it’s more natural to build things, thinking that humans will be in contact with software creations.</p><p>It’s not easy. I’m still learning. It’s necessary to practice a lot until understanding the main concepts of programming language. But I try and work until to do the things as exactly I want.</p><p>I understand that the IT world changes faster. I always have something new to learn, and every small learning is an essential part of high knowledge.</p><p>Because of this, I say: I’m a (non) tech girl! Learning how to code, every day!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d82d301cd4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>