{"componentChunkName":"component---src-templates-blog-post-js","path":"/introduction-to-react-difference-between-class-component-and-functional","result":{"data":{"contentfulBlogPost":{"createdAt":"2019-09-20T00:56:50.120Z","updatedAt":"2019-09-20T01:05:02.082Z","id":"be37ccf3-433a-5e1f-9269-e154c6d1c13a","description":"Are you new in React? Do you want to learn something new in 5 minutes or less?. Let’s learn about React components.","title":"An introduction to React: Difference between Class Component and Functional Component","body":{"id":"fd99f845-9938-5e23-a313-bd907228e109","childMarkdownRemark":{"id":"8525b06e-eee1-5d57-9320-6a3ea8b1047c","html":"<h2>What is a Component?</h2>\n<p>First of all, before we go deep in this topic, we should know perfectly what a component really is.</p>\n<p>A Component (in React) would be describe as an block or portion of our app which could be reuse in the entire project (and others, maybe), it is usually related with a <em>UI element</em> and its behavior.</p>\n<p>Now, assuming you know the basic, let’s check about the two types of component that we can create in a React project, <strong>Class Components</strong> and <strong>Functional Components</strong>.</p>\n<h2>Class Component</h2>\n<p>This is also called Basic Component. Since ECMAScript 2015, We have “class” in javascript. React uses this syntax to create a stateful component with lifecycle. The state is commonly used to change the behavior of our component or its children.</p>\n<pre><code class=\"language-javascript\">// App.js\nimport React from 'react'\nimport Lamp from 'Lamp'\n\nclass App extends React.Component {\n  render() {\n    return (\n      &#x3C;Lamp />\n    );\n  }\n}\n\nReactDOM.render(\n  &#x3C;App />,\n  document.getElementById('react-example')\n);\n</code></pre>\n<pre><code class=\"language-javascript\">// Lamp.js\nimport React from 'react'\n\nexport default class Lamp extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {\n      isTurnedOn : false\n    }\n  }\n\n  switchLight = () => {\n    this.setState({\n      isTurnedOn : !this.state.isTurnedOn\n    })\n  }\n\n  render() {\n    return (\n      &#x3C;div>\n        &#x3C;p>The lamp is &#x3C;b>{this.state.isTurnedOn ? 'on' : 'off'}&#x3C;/b>&#x3C;/p>\n        &#x3C;button onClick={this.switchLight}>switch&#x3C;/button>\n      &#x3C;/div>\n    )\n  }\n}\n</code></pre>\n<p>Let’s crack this code. Here we have a <em>“JS class”</em> which inherit functionality from React.Component, next we declare its constructor who received the <em>props</em> as argument. Next, we call <strong>super</strong>, to pass the data to the parent class <strong>Component</strong>, this is required when we create this type of component.</p>\n<blockquote>\n<p><em>The “props” is an object which got all the attributes when we use the component as a tag.</em></p>\n</blockquote>\n<p>The Lamp component has basic porpose, it <strong>render</strong> a HTML block with a text and a button.</p>\n<p>Clicking the button <strong>switch</strong> it turn on or off the lamp, here is where our state get into the game, in the line 4, we initialize the state of the Lamp, and after that, we declare the method <strong>switchLight</strong>, which it will turn the state of our lamp.</p>\n<blockquote>\n<p><em>this “state” is an object with some properties which will change in the time of the class execution.</em>\n<em>It shouldn’t be changed directly but using the setState method.</em></p>\n</blockquote>\n<p>You can change the state in this way to:</p>\n<pre><code class=\"language-javascript\">this.setState((state) => {\n    return { isTurnedOn: !state.isTurnedOn }\n})\n</code></pre>\n<hr>\n<h2>Functional Component</h2>\n<p>Now, if we want build some minimal, simple and stateless component, this will help you to reduce de amount of code used and apply the DRY principle easier. The funcional component is a javascript function that return one or some <em>Jxs elements</em>.</p>\n<p>Let’s check this example of a <strong>Bulb Component</strong>.</p>\n<pre><code class=\"language-javascript\">import React from 'react'\n\nexport default function Bulb({ lampState }) {\n  return lampState ?\n    (&#x3C;span>\n      &#x3C;img src={'https://cdn2.iconfinder.com/data/icons/flat-icons-19/512/Light_bulb.png'} width={50} />\n    &#x3C;/span>) :\n    (&#x3C;span>\n      &#x3C;img src={'https://img.icons8.com/ios/1600/light-on.png'} width={50} />\n    &#x3C;/span>)\n}\n</code></pre>\n<p>Right here, we have a regular function, it receive an <strong>destructured object</strong> with a property named <em>lampState</em>, it is turn to a local variable, and we evaluate if is true or false to return a different <em>img</em> tag.</p>\n<p>Now, we can use it in the Lamp component to show how their can work fine together.</p>\n<pre><code class=\"language-javascript\">// Lamp.js\nimport React from 'react'\nimport Bulb from 'Bulb'\n\nexport default class Lamp extends React.Component {\n  constructor(props) {\n    super(props)\n    this.state = {\n      isTurnedOn : false\n    }\n  }\n\n  switchLight = () => {\n    this.setState({\n      isTurnedOn : !this.state.isTurnedOn\n    })\n  }\n\n  render() {\n    return (\n      &#x3C;div>\n        &#x3C;Bulb lampState={this.state.isTurnedOn} />\n        &#x3C;p>The lamp is &#x3C;b>{this.state.isTurnedOn ? 'on' : 'off'}&#x3C;/b>&#x3C;/p>\n        &#x3C;button onClick={this.switchLight}>switch&#x3C;/button>\n      &#x3C;/div>\n    )\n  }\n}\n</code></pre>\n<p>That’s it, when we click the switch button, the image of the turned on bulb change.</p>\n<h2>What about Hooks?</h2>\n<p>Hooks are the latest feature that lets you use state in functional component. This need to be explained with more details, because we need to dig deeper in some new React concepts , i think it deserve its own article.</p>\n<p>Thank’s for reading, if you liked or not, give me you feedback.-</p>","excerpt":"What is a Component? First of all, before we go deep in this topic, we should know perfectly what a component really is. A Component (in React) would be describe as an block or portion of our app which could be reuse in the entire project (and others, maybe), it is usually…"}},"image":{"id":"e8dec582-860a-5774-b84f-ae1aa5b7cbad","fluid":{"base64":"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAALABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAUIB//EACYQAAEDAwMCBwAAAAAAAAAAAAECAwQABhEFMUESEyEiI1FhssH/xAAWAQEBAQAAAAAAAAAAAAAAAAAGBAX/xAAiEQABAwMDBQAAAAAAAAAAAAABAAIDBAYRBUGRFTFhcZL/2gAMAwEAAhEDEQA/AMduC/rSY0NpzTtRbjSF4Cmn0lKmyffw4+M0huG44duSoiXdV7yZIVltfqbY26P08jHNTTq0+S8olby1E75NLokh1DmErUAeAa1I9ZnaxFG2dSxSkiRxBJ74J5xt6VOxrvtZ5rqeRJacJOUpQnH2oqf2JDvbHnNFS9ZqPHCQi3KXZzvpf//Z","aspectRatio":1.881720430107527,"src":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=786&q=50","srcSet":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=197&h=105&q=50 197w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=393&h=209&q=50 393w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=700&h=372&q=50 700w","srcWebp":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=786&q=50&fm=webp","srcSetWebp":"//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=197&h=105&q=50&fm=webp 197w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=393&h=209&q=50&fm=webp 393w,\n//images.ctfassets.net/szbztvipepx3/2XJCAHhu03u7GAzyGSyXoS/9b4f6514448eeab52f8bd32ec74b0d63/react.jpg?w=700&h=372&q=50&fm=webp 700w","sizes":"(max-width: 786px) 100vw, 786px"}}}},"pageContext":{"slug":"introduction-to-react-difference-between-class-component-and-functional","intl":{"language":"en","languages":["en","es"],"messages":{"title":"Omar Gaston","navbar.knowme":"About me","navbar.projects":"Projects","navbar.contact":"Contacts","frontpage.readMyBlog":"Read my blog","frontpage.knowme":"Who am I?","blog.subtitle":"Creating stories.","blog.title":"Sharing my ideas","blog.text":"with the community.","subscribe":"Subscribe","changeLanguage":"ES","goBack":"Go back","viewOnGithub":"View on Github","viewProject":"View Project","viewMore":"See more","notFound.title":"NOT FOUND","notFound.text":"You just hit a route that doesn't exist... what sadness! ","notFound.knowAuthor":"well, this guy","notFound.goBlog":"Better go and read something","notFound.whoSay":"...Who say that?","personal.title":"Who I Am?","personal.fullname":"Omar Gaston Chalas","personal.salute":"Hi, I'm","personal.presentation":"A Javascript Full-Stack Developer, Lover of creating products which make people's life easier.","personal.presentationContinue":"I'm always eager to hear about new ideas, create and learn new things.","personal.coverletter":"Well I'm Omar, a Dominican Software Engineer passionate about Javascript, web development and related technologies. As a developer, I've been building highly scalable business apps for more than 3+ years caring deeply about the details in both well-crafted code and user-facing experience. ","personal.coverletterContinue":"Since I remember, I've always been curious and eager to learn new technologies and acquire new skills. Constant learning and a proactivity attitude have allowed me to be comfortable with the rapid changes which are already common in the modern tech industry.","personal.coverletterContinue2":"Despite I care about keeping my technical skills shaped, I also have a Startup mindset and pragmatic attitude, that comes with a willingness to lead projects and desire to understand about the business and where it’s heading","personal.quote":"It's not all about me, As a team player, I love collaborating with others and be involved in Open Source projects. For me, mentoring and helping others is the best way to giving back to those whos have led me in the past.","personal.coverletterFooter":"By the way, These are some of the tools I'm currently using: ","aptitudes.title":"Skills","aptitudes.creativity.title":"Creativity","aptitudes.creativity.text":"The best way to demonstrate authenticity is by being creative.","aptitudes.innovation.title":"Innovation","aptitudes.innovation.text":"Experiment and apply new technologies.","aptitudes.focused.title":"Focus","aptitudes.focused.text":"The correct solutions arise by dividing a problem and focusing on each part.","aptitudes.consistency.title":"Consistency","aptitudes.consistency.text":"The only way to achieve success is to persevere.","aptitudes.simplest.title":"Simplicity","aptitudes.simplest.text":"It's always good when something works, but when it's simple and works, it's wonderful.","aptitudes.community.title":"♥","aptitudes.community.text":"Work as a team with communities and colleagues.","projects.title":"Projects","projects.text":"Some of the projects I've been working on","contact.title":"Contact","contact.text":"Talk to me and work together.","contact.form.email.label":"Email","contact.form.email.placeholder":"Your email","contact.form.message.label":"Message","contact.form.message.placeholder":"Anything about you, your work or your pet :)","contact.form.submit":"Send","contact.form.secondmessage":"Tell me, what's going on?","contact.writeme":"Write me!","lastPost.title":"Latest posts","search.result":"result","search.noresult":"No results for","search.search":"Search"},"routed":false,"originalPath":"/introduction-to-react-difference-between-class-component-and-functional","redirect":false}}}}