<?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 Juliano Rafael on Medium]]></title>
        <description><![CDATA[Stories by Juliano Rafael on Medium]]></description>
        <link>https://medium.com/@frontendwizard?source=rss-ad9feaa3bec5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8_vnNsmHgMf4sdSjl3llOA.png</url>
            <title>Stories by Juliano Rafael on Medium</title>
            <link>https://medium.com/@frontendwizard?source=rss-ad9feaa3bec5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 20:30:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@frontendwizard/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[Ganchos? Vamos conversar sobre React hooks]]></title>
            <link>https://medium.com/getty-io/ganchos-vamos-conversar-sobre-react-hooks-1d4309e7b4c0?source=rss-ad9feaa3bec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d4309e7b4c0</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[padrões]]></category>
            <dc:creator><![CDATA[Juliano Rafael]]></dc:creator>
            <pubDate>Mon, 29 Oct 2018 12:14:21 GMT</pubDate>
            <atom:updated>2018-10-29T12:14:21.048Z</atom:updated>
            <content:encoded><![CDATA[<h4>O que são hooks e como isso muda a maneira de construir componentes com React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*El0cjv5zkNj4zfkofSvvFw.jpeg" /><figcaption>Proposta dos hooks sendo apresentada por <a href="https://twitter.com/dan_abramov">Dan Abramov</a> e <a href="https://twitter.com/sophiebits">Sophie Alpert</a></figcaption></figure><p>React Conf 2018 veio e com ela vieram muitas novidades e features para melhorar tanto a performance de nossos apps e a nossa vida como programador, assim como também para melhorar a clareza do código e diminuir a curva de aprendizado.</p><p>Enquanto a gente já tinha sido apresentado ao React Suspense, que melhora bastante a experiência do usuário diminuindo a quantidade de spinners na tela e só mostrando-os quando necessário, hooks foi uma surpresa para todos pois a proposta foi mantida em segredo até o evento. E sério, precisamos falar sobre isso, porque vai mudar a maneira como escrevemos componentes nos nossos apps.</p><h3>O que são Hooks?</h3><p><em>Ganchos. Brincadeira. Quer dizer, é praticamente isso mesmo.</em></p><p>Para entender hooks, primeiro precisamos falar sobre componentes. Hoje a gente tem dois tipos de componentes no React, os que são somente uma função, onde é renderizado o que é retornado desta, e os que são classes, que te dão um poder maior para utilizar estado e métodos de ciclo de vida. As funções são mais performáticas mas não tem acesso ao estado ou ao ciclo de vida dos componentes. Melhor dizendo, <strong>não tinham</strong>. Agora tem. 🎉🎉🎉🎉</p><p>Os hooks vem pra endereçar exatamente esse problema. Agora as funções também vão poder ter estado e usar os métodos de ciclo de vida.</p><h4>Ok, a gente já podia fazer isso com classe, qual a diferença?</h4><p>Pergunta justa. Então vamos comparar as duas formas.</p><p>Vamos escrever um componente simples, o contador. Ele mostra a contagem, tem um botão de incremento e decremento e ele armazena a contagem no estado.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S-K_hA-I1-ZroqOWUzrdkQ.png" /><figcaption>Contador feito com classe</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fpj8z7vq08x&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fpj8z7vq08x&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fpj8z7vq08x%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/55d0a60606225b574fb82962e4d81d8c/href">https://medium.com/media/55d0a60606225b574fb82962e4d81d8c/href</a></iframe><p>Podemos simplificar isso um pouco usando <a href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow functions</a> e <a href="https://github.com/tc39/proposal-class-fields">class fields</a>, mas não vai fugir muito disso e a segunda ainda não faz parte do JavaScript oficialmente. Mas funciona. Será que dá pra melhorar isso? E se a gente pudesse escrever isso usando somente funções, exigem menos código e são até mais performáticas.</p><p>Bom, eu lhes apresento o useState hook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBDMUgMP5da9yyB5FgIsKg.png" /><figcaption>Contador com useState hook</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F1zz824xmxl&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F1zz824xmxl&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F1zz824xmxl%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d8c74c01f7cdf1ef5ccb41d33dbbfe0/href">https://medium.com/media/3d8c74c01f7cdf1ef5ccb41d33dbbfe0/href</a></iframe><p>Consideravelmente mais simples e o mais importante, mais fácil de ler. Seu futuro você vai te agradecer. Porém o mais importante não é isso. Bora conversar sobre reutilização de código.</p><h3>Reutilização de código</h3><p>Pra poder reutilizar lógica entre componentes feitos com classe nós temos dois padrões bem estabelecidos na comunidade, <a href="https://reactjs.org/docs/higher-order-components.html">Higher Order Components</a> e <a href="https://reactjs.org/docs/render-props.html">Render Props</a>. Ambos são bons padrões e possibilitam a reutilização de funcionalidades entre diversos components. O problema é que ambos adicionam um nível de abstração na árvore da sua aplicação, te levando para o <em>Wrapper Hell</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*GrwxOuNuPVxI6YzWdCFqog.png" /><figcaption>Um exemplo de Wrapper Hell</figcaption></figure><p>Isso torna a aplicação complicada de debugar. Com hooks, todos esses componentes poder ser abstraídos em hooks e <strong>não há mais a necessidade de adicionar um nível na árvore</strong>.</p><p><em>Só cuidado para não cair no hook hell</em>. Brincadeira. Mas se algum dia ouvir isso, lembre-se de que viu primeiro aqui…</p><h4>E tem mais…</h4><p>useState é só um dos hooks que foram apresentados. Temos muitos outros e também podemos criar nossos próprios hooks utilizando-os, abstraindo as funcionalidades em funções e usando-as aonde for necessário.</p><p>Os principais hooks são 3, categorizados como hooks básicos são:</p><ul><li>useState: que permite ler e armazenar informações no estado.</li><li>useEffect: que permite executar <em>side effects</em> (efeitos colaterais) no seu componente. Útil para executar ações no ciclo de vida do componente, como fazemos com componentDidMount e componentDidUpdate nas classes.</li><li>useContext: Nos permite usar o Context e compartilhar estado entre os componentes filhos de um Provider.</li></ul><p>Dominando esses três tu já <strong>vai poder dominar o mundo</strong>. 😃 Ok, talvez não o mundo, mas tu já vai poder fazer o que fazemos com classes hoje, usando componentes funcionais e mantendo seu código mais enxuto.</p><p>Temos também hooks adicionais, que são para casos mais específicos e variações dos três anteriores. Esses são:</p><ul><li>useReducer: hook pra usar o padrão utilizado no redux.</li><li>useCallback: permite criar uma callback memorizada. Isso é útil para acelerar componentes filho que recebem callback, evitando que eles renderizem novamente caso o valor não mude.</li><li>useMemo: permite a criação de um valor memorizado. useCallback(fn, inputs) é equivalente de useMemo(() =&gt; fn, inputs).</li><li>useRef: permite a utilização de uma referência para um elemento para acesso posterior.</li><li>useImperativeMethods: permite a customização da instância que é exposta e é utilizada junto com forwardRef. Seu uso deve ser evitado.</li><li>useMutationEffect: idêntico ao useEffect, mas acontece de maneira síncrona, na mesma fase em que o React faz suas mutações na DOM.</li><li>useLayoutEffect: idêntico ao useEffect, mas é disparado <em>depois</em> de todas as mutações na DOM.</li></ul><p>Tanto useMutationEffect quanto useLayoutEffect devem ser evitados para não bloquear updates na DOM.</p><h3>Morte a todas as classes! Vamos refatorar todas para funções!</h3><p>Woooa, calma ae. Eu sei que tu tá animado que nem eu, mas na real, não há a necessidade de refatorar, muito menos de uma só vez. Isto tudo ainda é só uma proposta e não quebra em nada a API que existe no momento, ou seja, suas classes ainda vão ser úteis e vão continuar funcionando.</p><p>O que se espera é que ocorra uma mudança gradual. Novos componentes agora podem ser escritos com hooks e provavelmente componentes muito utilizados serão refatorados para melhorar a legibilidade do código e facilitar a vida de todo mundo no seu time quando alguém tiver que trabalhar novamente com ele.</p><p>Tu pode começar a brincar com hooks já usando a versão 16.7.0-alpha.0 do react e react-dom e participar da discussão aberta <a href="https://github.com/reactjs/rfcs/pull/68">aqui</a>.</p><h3>Saiba mais</h3><p>Curioso? Quer saber mais? Segue aí uns links pra você se aprofundar no assunto:</p><p>Primeiramente, assista a talk sensacional do <a href="https://twitter.com/dan_abramov">Dan Abramov</a> e da sensacional <a href="https://twitter.com/sophiebits">Sophie Alpert</a>: <a href="https://www.youtube.com/watch?v=dpw9EHDh2bM">https://www.youtube.com/watch?v=dpw9EHDh2bM</a></p><p>Depois, mergulhe fundo na documentação do React. Tem uma sessão especial só para os hooks: <a href="https://reactjs.org/docs/hooks-intro.html">https://reactjs.org/docs/hooks-intro.html</a></p><p>Animado? Comenta aqui em baixo o que tu achou da proposta e quantos componentes tu já quer refatorar com os “ganchos”. 😂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d4309e7b4c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getty-io/ganchos-vamos-conversar-sobre-react-hooks-1d4309e7b4c0">Ganchos? Vamos conversar sobre React hooks</a> was originally published in <a href="https://medium.com/getty-io">Getty/IO Blog - The Blockchain Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Never Repeat PropTypes Declarations Again]]></title>
            <link>https://medium.com/getty-io/how-to-never-repeat-proptypes-declarations-again-abff2457c34c?source=rss-ad9feaa3bec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/abff2457c34c</guid>
            <category><![CDATA[prop-types]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Juliano Rafael]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 01:18:05 GMT</pubDate>
            <atom:updated>2018-07-11T12:38:12.845Z</atom:updated>
            <content:encoded><![CDATA[<h4>I know you did this at least once</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rf__8xWSTniXUDcGvnC3Hw.jpeg" /></figure><p>You’re a front-end developer who works with React. Tell me in the comments, how many times did you repeat your PropTypes declaration on a parent component? How many times did you wished there was a better way of doing it? Well there is, and is stupidly simple. Seriously you’re going to feel angry with yourself about this one. I know I do.</p><p>Imagine the following situation: You gotta develop a list container and a item component. Something on these lines:</p><pre>import React from &#39;react&#39;<br>import PropTypes from &#39;prop-types&#39;</pre><pre>// Item component with its propTypes<br>const Item = ({ name }) =&gt; (<br>  &lt;li&gt;{name}&lt;/li&gt;<br>)<br><br>Item.propTypes = {<br>  name: PropTypes.string.isRequired<br>}<br><br>export default Item</pre><p>Notice the parent <strong>propTypes</strong> declaration:</p><pre>import React from &#39;react&#39;<br>import PropTypes from &#39;prop-types&#39;<br><br>import Item from &#39;./Item&#39; // suppose they are on the same directory<br><br>class ListContainer extends React.Component {<br>  static propTypes = {<br>    data: PropTypes.arrayOf(PropTypes.shape(Item.propTypes))<br>  }<br><br>  // usually data fetching logic<br><br>  render() {<br>    return (<br>      &lt;&gt;<br>        &lt;h1&gt;List of people&lt;/h1&gt;<br>        &lt;ul&gt;<br>          {this.props.data.map(item =&gt; &lt;Item {...item} /&gt;)}<br>        &lt;/ul&gt;<br>      &lt;/&gt;<br>    )<br>  }<br>}<br><br>export default ListContainer</pre><p>Did you notice the <strong>List</strong> <strong>Container</strong> <strong>propTypes</strong> <strong>declaration</strong>? It’s kinda obvious and simple, but I assure you that I cannot remember how many times I’ve seen (<em>and did. Yes, I admit.)</em> copy pasted declaration of child elements propTypes there. Not only it’s bad because you’re repeating itself, but it’s also a nightmare to maintain once the requirements change on the child component.</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>Conclusion</h4><p>As usual, the DRY principle stands high. If you’re repeating yourself while coding, stop! That’s a code smell and there must be a better way to do it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F11lfKIu2CxGHZe%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fthe-matrix-hugo-weaving-agent-smith-11lfKIu2CxGHZe&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F11lfKIu2CxGHZe%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="186" frameborder="0" scrolling="no"><a href="https://medium.com/media/6064c84d1e0d1d9e1536d771498d8239/href">https://medium.com/media/6064c84d1e0d1d9e1536d771498d8239/href</a></iframe><h3>Connect</h3><figure><a href="https://getty.io/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-MrLMf1P7azb9vJrDhu6A.png" /></a><figcaption><a href="https://getty.io/">https://getty.io</a></figcaption></figure><p>You need the right digital transformation strategy that will allow you to grow your company in a scalable way. Here at <strong>GETTY/IO</strong> we are a boutique software development firm, delivering tailored digital solutions to clients worldwide. With our out-of-the-box thinking and diverse expertise, we bring ideas to life much faster.</p><p>We offer comprehensive technological solutions that are tailored to fit the unique case of each project. If you have ideas, we have the strategy to implement them. With decades of experience in designing and creating outstanding applications, we’ll go the extra mile to bring you the most cost-effective solutions for your tech-related needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqHrtFkvnJskfaCcM9dQBQ.png" /><figcaption>Software Architecture Models</figcaption></figure><p>With our expertise across the latest digital solutions, we have what it takes to streamline business processes and add value. Whether you want to convert your ideas into an MVP or build new products or solutions using modern infrastructure, we can help. We’re passionate about developing mobile and web software for companies of all sizes, and we have the right talent to implement digital innovation programs from Start to Scale successfully. We’re here to help you innovate rapidly.</p><p>Say hello to us at <a href="http://hello@getty.io/">hello@getty.io</a></p><h4>Related Articles</h4><ul><li><a href="https://blog.getty.io/teste-de-software-moderno-fundamentos-do-teste-de-software-1b5a4866dc2f">Teste de Software Moderno: Fundamentos do Teste de Software</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-qualidade-%C3%A9-requisito-abc9a6e6ed74">Teste de Software Moderno: Qualidade é Requisito</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-dicion%C3%A1rio-de-termos-em-teste-de-software-d59e5da817c2">Teste de Software Moderno: Dicionário de Termos em Teste de Software</a></li><li><a href="https://blog.getty.io/falhas-na-nuvem-como-proteger-sua-empresa-deste-vil%C3%A3o-invis%C3%ADvel-567e769fd01c">Falhas Na Nuvem: Como Proteger Sua Empresa Deste Vilão Invisível</a></li><li><a href="https://blog.getty.io/debugando-react-native-no-android-via-wi-fi-cedce242c375">Debugando React Native No Android Via Wi-Fi</a></li><li><a href="https://medium.com/getty-blog-brasil/como-criar-aplicativos-para-ios-e-android-com-a-metade-do-investimento-f3d474aafa8d">Como Criar Aplicativos Para iOS e Android com a Metade do Investimento</a></li><li><a href="https://medium.com/getty-blog-brasil/engenharia-de-software-na-getty-io-ade84e536eea">Engenharia de Software na Getty/IO</a></li><li><a href="https://medium.com/getty-blog-brasil/react-native-para-projetos-nativos-74fa562b53f">React Native Para Projetos Nativos</a></li><li><a href="https://medium.com/getty-blog-brasil/aplica%C3%A7%C3%B5es-escal%C3%A1veis-com-react-e-react-native-2d337deaf8a1">Aplicações Escaláveis com React e React Native</a></li><li><a href="https://medium.com/getty-blog-brasil/excel%C3%AAncia-em-desenvolvimento-de-software-91816efd87f1">Excelência em Desenvolvimento de Software</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abff2457c34c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getty-io/how-to-never-repeat-proptypes-declarations-again-abff2457c34c">How to Never Repeat PropTypes Declarations Again</a> was originally published in <a href="https://medium.com/getty-io">Getty/IO Blog - The Blockchain Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Desenvolvendo Apps com Styled-Components]]></title>
            <link>https://medium.com/getty-io/desenvolvendo-apps-com-styled-components-85ec6880b194?source=rss-ad9feaa3bec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ec6880b194</guid>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Juliano Rafael]]></dc:creator>
            <pubDate>Fri, 09 Feb 2018 15:00:21 GMT</pubDate>
            <atom:updated>2018-02-09T15:00:21.737Z</atom:updated>
            <content:encoded><![CDATA[<h4>Porque usamos? É bom o suficiente para por em produção?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TqPNtQcP2Wk6PN2vxtoaA.png" /></figure><p>Na <a href="https://getty.io/">Getty/IO</a> nós usamos <a href="http://styled-components.com/">styled-components</a>. Sim, e você pode estar se perguntando, porquê? Essa não é mais uma daquelas libs para escrever CSS no JS? Isso é realmente uma boa ideia? E a reusabilidade do CSS com as classes? Essa são questões válidas e interessantes e são estas que vou endereçar nesse artigo.</p><h4>Porquê? Styled-components não é somente mais uma daquelas libs de CSS no JS?</h4><p>Sim, styled-components é mais uma lib de CSS em JS e pra ser honesto, CSS em JS parece um anti-pattern de início. Mas o ponto chave de styled-components é o React. Styled-components encaixa perfeitamente com a maneira de se pensar ao desenvolver um app com React <strong>porque transforma seu CSS em componentes</strong>.</p><p>Você pode usar CSS ou mesmo Sass para desenvolver suas aplicações? Claro. Mas vamos ser sinceros, os maiores problemas dessa abordagem são nomear e ativar e desativar classes. Para alternar uma classe você precisa criar uma string com e sem a classe e alternar entre elas ao passar a prop className para o componente. Isso nos leva a um código do tipo:</p><pre>&lt;Component className={active ? &quot;component active&quot; : &quot;component&quot;} /&gt;</pre><p>Ou qualquer outro método de manipulação de string que você preferir. Mas no fim, esse gerenciamento tem que ser feito manualmente e esse código simplesmente é feio e não escala. Imagine que você tem mais duas ou três classes que alternam.</p><p>Com styled-components, podemos adaptar o css de acordo com as props do componente, o que nos leva a:</p><pre>&lt;Component active={true} /&gt;</pre><p>E o css vai responder de acordo. Muito mais limpo e coerente.</p><h3>Reusabilidade</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx7KNaTteVDA1XyMD37mjQ.jpeg" /></figure><p>Com CSS podemos criar classes que podem ser usadas em vários locais diferentes de nossa aplicação. Isso é uma boa prática e mantém nosso código condizente com o princípio DRY (<em>Don’t Repeat Yourself</em>, que significa algo como: não repita).</p><p>Com styled-components a reusabilidade vem com os componentes. Você pode criar um botão, por exemplo, e reutilizar este em toda a sua aplicação. E não importa se você tem vários tipos de botões na sua aplicação, você pode ir criando propriedades que ajustam seu botão para as necessidades daquele local.</p><pre>import styled, { css } from &#39;styled-components&#39;<br>import PropTypes from &#39;prop-types&#39;</pre><pre>const Button = styled.button`<br>  background-color: #000000;<br>  color: #FFFFFF;<br>  ${props =&gt; props.rounded &amp;&amp; css`<br>    border-radius: 5px;<br>  `}<br>  ${props =&gt; props.outline &amp;&amp; css`<br>    background-color: transparent;<br>    border: 1px solid #000000;<br>    color: #000000;<br>  `}<br>`</pre><pre>Button.propTypes = {<br>  rounded: PropTypes.bool,<br>  outline: PropTypes.bool<br>}</pre><pre>export default Button</pre><p>E simples assim temos um botão que por default renderiza com o fundo preto e um botão com o fundo transparente e uma borda com o texto da mesma cor, ambos com um border-radius opcional. Basta que passemos a prop adequada e o componente vai se adaptar de acordo. E o mais legal, <strong>isso funciona praticamente da mesma maneira no React Native</strong>.</p><h3>Ok, entendi seu argumento. O que mais posso fazer com styled-components?</h3><p>Que bom que você perguntou :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4XOiaOvzMwgYN-BFx0Plg.png" /></figure><h4>Temas</h4><p>Imagine a seguinte situação: Você tem um app que normalmente renderiza seu conteúdo sobre um fundo branco. Porém em uma sessão, o background é escuro e seu texto precisa se adaptar de acordo. Com CSS faríamos algo do tipo:</p><pre>.darkSection p {<br>  color: #FFFFFF;<br>}</pre><p>O que também pode ser feito com styled-components:</p><pre>const darkSection = styled.div`<br>  p {<br>    color: #FFFFFF;<br>  }<br>`</pre><p>Na web funcionaria bem pois podemos selecionar elementos no CSS. O mesmo não é válido no React Native. Mas isso pode ser melhor.</p><p>No styled-components temos um componente chamado ThemeProvider. Esse componente provê um objeto chamado theme para todos os seus componentes filhos, não importando quão fundo eles estejam na árvore.</p><p>Então, ao invés de fazermos como demonstrado acima, fazemos:</p><pre>const P = styled.p`<br>  color: ${props =&gt; props.theme.color};<br>`<br>P.defaultProps = {<br>  theme: {<br>    color: #000000;<br>  }<br>}</pre><p>Agora nosso componente renderiza o texto preto por padrão. Porém, se uma prop theme for passa a ele com a cor do texto, ele vai se adaptar de acordo.</p><p>Tudo o que precisamos fazer agora é envolver nossa sessão escura em um ThemeProvider.</p><pre>import { ThemeProvider } from &#39;styled-components&#39;</pre><pre>const DarkSection = () =&gt; (<br>  &lt;ThemeProvider theme={{ color: &#39;#000000&#39; }}&gt;<br>    /* dark section content */<br>  &lt;/ThemeProvider&gt;<br>)</pre><p>E todo componente P em nossa sessão escura vai renderizar seu texto na cor branca. Um pouco mais elabora, mas também mais poderoso. Esse objeto theme pode armazenar literalmente qualquer coisa que um objeto pode e podemos moldar o css de nossos componentes de acordo. Isso torna a criação de temas muito fácil.</p><p>Se estiver interessado em temas, talvez você queira conferir a lib <a href="https://github.com/styled-components/polished">polished</a>, que é uma lib de utilitários que funciona lindamente com styled-components.</p><h4>Extendendo estilos</h4><p>Podemos também extender estilos de outro componente criado com styled-components.</p><p>Imagine que temos um componente Image como a seguir:</p><pre>const Image = styled.img`<br>  width: ${props =&gt; props.width};<br>  height: ${props =&gt; props.height};<br>`<br>Image.defaultProps = {<br>  width: &#39;100%&#39;,<br>  height: &#39;auto&#39;<br>}</pre><p>E que queremos extender os estilos desse componente para a Logo com um CSS relacionado somente a este caso:</p><pre>const Logo = Image.extend`<br>  @media only screen and (max-width: 600px) {<br>    height: ${props =&gt; props.height || &#39;47px&#39;};<br>  }<br>  @media only screen and (min-width: 601px) and (max-width: 1024px) {<br>    height: ${props =&gt; props.height || &#39;60px&#39;};<br>  }<br>  @media only screen and (min-width: 1025px) {<br>    height: ${props =&gt; props.height || &#39;70px&#39;};<br>  }<br>`</pre><p>Poderíamos também já configurar o atributo source nesse caso para não termos que digita-lo ao usar o componente:</p><pre>const Logo = Image.extend.attrs({<br>  src: &quot;url(https://www.image.url/)&quot;<br>})`<br>  /* CSS */<br>`</pre><h3>Conclusão</h3><p>Bom, eu confesso que sou suspeito ao falar de styled-components pois eu realmente gosto dessa lib. Ela me trouxe de volta o sentimento de quando eu descobri o Sass e o quão legal era poder concatenar declarações de estilos e usar os super poderes do Sass. Então veio o React e mudou a maneira como pensamos sobre construir aplicações, pensando em componentes, inclusive no CSS. E o styled-components se encaixa perfeitamente nesse paradigma.</p><p>A questão final: <strong>Styled-components é bom o suficiente para o ambiente de produção?</strong> A resposta claramente é sim. Essa lib torna desenvolver componentes de UI muito intuitivo e tem um sólido suporte a temas.</p><h3>Connect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ol-ANjwA9jqOs4CwySRdw.png" /></figure><p>Se você tem desafios na sua empresa em relação à desenvolvimento de um PWA, envie uma mensagem para <strong>hello@getty.io</strong>, nós podemos te ajudar.</p><p>Juntos, imaginamos e criamos aplicações web e mobile que escalam automaticamente e estão sempre disponíveis a partir de qualquer dispositivo em qualquer lugar.</p><h3>Artigos Relacionados</h3><ul><li><a href="https://blog.getty.io/importance-of-continuous-integration-on-software-development-30ab74c61c1">The Importance of Continuous Integration in Software Development</a></li><li><a href="https://blog.getty.io/10-motivos-para-usar-redux-em-2018-96664e124425">10 Motivos Para Usar Redux em 2018</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-fundamentos-do-teste-de-software-1b5a4866dc2f">Teste de Software Moderno: Fundamentos do Teste de Software</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-qualidade-%C3%A9-requisito-abc9a6e6ed74">Teste de Software Moderno: Qualidade é Requisito</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-dicion%C3%A1rio-de-termos-em-teste-de-software-d59e5da817c2">Teste de Software Moderno: Dicionário de Termos em Teste de Software</a></li><li><a href="https://blog.getty.io/falhas-na-nuvem-como-proteger-sua-empresa-deste-vil%C3%A3o-invis%C3%ADvel-567e769fd01c">Falhas Na Nuvem: Como Proteger Sua Empresa Deste Vilão Invisível</a></li><li><a href="https://blog.getty.io/debugando-react-native-no-android-via-wi-fi-cedce242c375">Debugando React Native No Android Via Wi-Fi</a></li><li><a href="https://medium.com/getty-blog-brasil/como-criar-aplicativos-para-ios-e-android-com-a-metade-do-investimento-f3d474aafa8d">Como Criar Aplicativos Para iOS e Android com a Metade do Investimento</a></li><li><a href="https://medium.com/getty-blog-brasil/engenharia-de-software-na-getty-io-ade84e536eea">Engenharia de Software na Getty/IO</a></li><li><a href="https://medium.com/getty-blog-brasil/react-native-para-projetos-nativos-74fa562b53f">React Native Para Projetos Nativos</a></li><li><a href="https://medium.com/getty-blog-brasil/aplica%C3%A7%C3%B5es-escal%C3%A1veis-com-react-e-react-native-2d337deaf8a1">Aplicações Escaláveis com React e React Native</a></li><li><a href="https://medium.com/getty-blog-brasil/excel%C3%AAncia-em-desenvolvimento-de-software-91816efd87f1">Excelência em Desenvolvimento de Software</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ec6880b194" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getty-io/desenvolvendo-apps-com-styled-components-85ec6880b194">Desenvolvendo Apps com Styled-Components</a> was originally published in <a href="https://medium.com/getty-io">Getty/IO Blog - The Blockchain Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing Apps With Styled-Components]]></title>
            <link>https://medium.com/getty-io/developing-apps-with-styled-components-e9f56cd0f4c5?source=rss-ad9feaa3bec5------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f56cd0f4c5</guid>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Juliano Rafael]]></dc:creator>
            <pubDate>Thu, 08 Feb 2018 15:29:34 GMT</pubDate>
            <atom:updated>2018-02-27T13:34:28.716Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why do we use it? Is it good enough for production?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TqPNtQcP2Wk6PN2vxtoaA.png" /></figure><p>At <a href="https://getty.io/">Getty/IO</a> we use and love <a href="http://styled-components.com/">styled-components</a>. You may ask me, why? Isn’t just another CSS-in-JS lib? Is it really a good idea to write CSS-in-JS? What about CSS reusability with classes? Those are super valid questions and I’ll try to answer them now.</p><h4>Isn’t styled-components just another CSS-in-JS lib?</h4><p>Yes it is. And to be fair, CSS-in-JS does look like a bad idea. But the key point of styled-components is React. Styled-components fits perfectly on the React mindset for developing applications because <strong>styled-components turns css into presentational components</strong>. This is important.</p><p>You can use Sass or even pure CSS to develop your applications? For sure. But, lets be honest, the biggest pain point of this approach are classes names and class toggling. To toggle classes you need to manually create a string with and without the classes and pass it to the className prop. This leads to code like this:</p><pre>&lt;Component className={active ? &quot;component active&quot; : &quot;component&quot;} /&gt;</pre><p>Or any other string manipulation method you prefer. But the point stands. This looks terrible. With styled-components, we can adapt the css based on the props of the component. Leading to this:</p><pre>&lt;Component active /&gt;</pre><p>And the css will answer accordingly. Much cleaner.</p><h3>Reusability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx7KNaTteVDA1XyMD37mjQ.jpeg" /></figure><p>With CSS we can create good classes that can be used many times throughout our application. This is a good practice and keep our code compliant with the DRY principle.</p><p>With styled-components, the reusability is about the components. You can create a button, for example, and reuse throughout the application. It doesn’t matter if you have multiple types of button. You can create multiple props that adjust the button as you need.</p><pre>import styled, { css } from &#39;styled-components&#39;<br>import PropTypes from &#39;prop-types&#39;</pre><pre>const Button = styled.button`<br>  background-color: #000000;<br>  color: #FFFFFF;<br>  ${props =&gt; props.rounded &amp;&amp; css`<br>    border-radius: 5px;<br>  `}<br>  ${props =&gt; props.outline &amp;&amp; css`<br>    background-color: transparent;<br>    border: 1px solid #000000;<br>    color: #000000;<br>  `}<br>`</pre><pre>Button.propTypes = {<br>  rounded: PropTypes.bool,<br>  outline: PropTypes.bool<br>}</pre><pre>export default Button</pre><p>And just like that you have both a default Button with a black background or a outline Button with transparent background and border, both with an optional border-radius. <strong>The exactly same idea works both on the web and on React Native</strong>.</p><h3>Ok, you made your point. What else can I do with styled-components?</h3><p>Glad you asked :)</p><h4>Themes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4XOiaOvzMwgYN-BFx0Plg.png" /></figure><p>Lets imagine the following situation: You have an app that normally displays text on white background. At one section though, the background is dark and your text need to adapt it accordingly. With css we would do something like this:</p><pre>.darkSection p {<br>  color: #FFFFFF;<br>}</pre><p>We could do that with styled-components:</p><pre>const darkSection = styled.div`<br>  p {<br>    color: #FFFFFF;<br>  }<br>`</pre><p>At least on the web you can, because you can select elements. That wouldn’t work on React Native. And it’s not that good.</p><p>On styled-components, there’s a component called ThemeProvider. This component provides an object called theme though props to its children. No matter how deep they are.</p><p>So, instead of doing that, we do this:</p><pre>const P = styled.p`<br>  color: ${props =&gt; props.theme.color};<br>`<br>P.defaultProps = {<br>  theme: {<br>    color: #000000;<br>  }<br>}</pre><p>Now, our component by default renders with black text. But, if a theme prop is passed down to it, it’ll change it’s color accordingly.</p><p>All we need to do now is to wrap our dark section with a ThemeProvider.</p><pre>import { ThemeProvider } from &#39;styled-components&#39;</pre><pre>const DarkSection = () =&gt; (<br>  &lt;ThemeProvider theme={{ color: &#39;#000000&#39; }}&gt;<br>    /* dark section content */<br>  &lt;/ThemeProvider&gt;<br>)</pre><p>And every P component on our dark section will render its text white. A bit more elaborate, but also more powerful. This theme object can hold literally anything an object can hold and we can shape our components css accordingly. This makes theming apps really easy.</p><p>If you’re interested in theming, you might want to check <a href="https://github.com/styled-components/polished">polished</a>, which is a utils lib that works beautifully with styled-components.</p><h4>Extending styles</h4><p>We can also extend styles from another styled component.</p><p>Imagine we have a Image component like this one:</p><pre>const Image = styled.img`<br>  width: ${props =&gt; props.width};<br>  height: ${props =&gt; props.height};<br>`<br>Image.defaultProps = {<br>  width: &#39;100%&#39;,<br>  height: &#39;auto&#39;<br>}</pre><p>And we want to extend this component for a Logo image with special responsiveness css related only to it:</p><pre>const Logo = Image.extend`<br>  @media only screen and (max-width: 600px) {<br>    height: ${props =&gt; props.height || &#39;47px&#39;};<br>  }<br>  @media only screen and (min-width: 601px) and (max-width: 1024px) {<br>    height: ${props =&gt; props.height || &#39;60px&#39;};<br>  }<br>  @media only screen and (min-width: 1025px) {<br>    height: ${props =&gt; props.height || &#39;70px&#39;};<br>  }<br>`</pre><p>We could also setup the source attribute for this one so that we don’t have to type it when using the component like this:</p><pre>const Logo = Image.extend.attrs({<br>  src: &quot;url(https://www.image.url/)&quot;<br>})`<br>  /* CSS */<br>`</pre><h3>Conclusion</h3><p>Well, I confess, I’m biased towards styled-components because I truly love this lib. It brought me back to the time when I discovered Sass and how awesome it was to be able to concatenate css and use all the other Sass super powers. Then React came and changed the way we think about applications, thinking in components all the way through, including in CSS. And styled-components fits perfectly on this paradigm.</p><p>The final question stands: <strong>Is it good enough for production? </strong>The answer is a clear yes. This lib makes developing UI components a joy and with a solid support for themes.</p><h3>Connect</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ol-ANjwA9jqOs4CwySRdw.png" /></figure><p>With our expertise across the latest digital solutions, we have what it takes to streamline business processes and add value. Whether you want to convert your ideas into an MVP or build new products or solutions using modern infrastructure, we can help. We’re passionate about developing mobile and web software for companies of all sizes, and we have the right talent to implement digital innovation programs from Start to Scale successfully. We’re here to help you innovate rapidly.</p><p>Say hello to us at <a href="http://hello@getty.io/">hello@getty.io</a></p><h3>Related Articles</h3><ul><li><a href="https://blog.getty.io/importance-of-continuous-integration-on-software-development-30ab74c61c1">The Importance of Continuous Integration in Software Development</a></li><li><a href="https://blog.getty.io/10-motivos-para-usar-redux-em-2018-96664e124425">10 Motivos Para Usar Redux em 2018</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-fundamentos-do-teste-de-software-1b5a4866dc2f">Teste de Software Moderno: Fundamentos do Teste de Software</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-qualidade-%C3%A9-requisito-abc9a6e6ed74">Teste de Software Moderno: Qualidade é Requisito</a></li><li><a href="https://blog.getty.io/teste-de-software-moderno-dicion%C3%A1rio-de-termos-em-teste-de-software-d59e5da817c2">Teste de Software Moderno: Dicionário de Termos em Teste de Software</a></li><li><a href="https://blog.getty.io/falhas-na-nuvem-como-proteger-sua-empresa-deste-vil%C3%A3o-invis%C3%ADvel-567e769fd01c">Falhas Na Nuvem: Como Proteger Sua Empresa Deste Vilão Invisível</a></li><li><a href="https://blog.getty.io/debugando-react-native-no-android-via-wi-fi-cedce242c375">Debugando React Native No Android Via Wi-Fi</a></li><li><a href="https://medium.com/getty-blog-brasil/como-criar-aplicativos-para-ios-e-android-com-a-metade-do-investimento-f3d474aafa8d">Como Criar Aplicativos Para iOS e Android com a Metade do Investimento</a></li><li><a href="https://medium.com/getty-blog-brasil/engenharia-de-software-na-getty-io-ade84e536eea">Engenharia de Software na Getty/IO</a></li><li><a href="https://medium.com/getty-blog-brasil/react-native-para-projetos-nativos-74fa562b53f">React Native Para Projetos Nativos</a></li><li><a href="https://medium.com/getty-blog-brasil/aplica%C3%A7%C3%B5es-escal%C3%A1veis-com-react-e-react-native-2d337deaf8a1">Aplicações Escaláveis com React e React Native</a></li><li><a href="https://medium.com/getty-blog-brasil/excel%C3%AAncia-em-desenvolvimento-de-software-91816efd87f1">Excelência em Desenvolvimento de Software</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f56cd0f4c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/getty-io/developing-apps-with-styled-components-e9f56cd0f4c5">Developing Apps With Styled-Components</a> was originally published in <a href="https://medium.com/getty-io">Getty/IO Blog - The Blockchain Company</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>