{"id":6533,"date":"2023-03-20T04:55:35","date_gmt":"2023-03-20T04:55:35","guid":{"rendered":"https:\/\/studysection.com\/blog\/?p=6533"},"modified":"2023-03-20T04:55:35","modified_gmt":"2023-03-20T04:55:35","slug":"constructor-method-in-reactjs","status":"publish","type":"post","link":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/","title":{"rendered":"Constructor() method in ReactJS"},"content":{"rendered":"<p>A constructor() is a method that is launched whenever an object of that class is created. It can do initialization operations like setting certain object properties to their default values or validating the input arguments.<br \/>\nIn React, a constructor() is the same, just like in other frameworks. It can initialize the local state of the component and also connect event handlers to it. The constructor() is used before the component is mounted and, like most things in React, has a few simple guidelines you can follow when using it.<\/p>\n<p><strong>Step 1:<\/strong> Call super(props) before using this.props<br \/>\nDue to the nature of the constructor, this.props object is not accessible directly, which can lead to errors. An error will be given by this constructor:<br \/>\n<code>constructor() {<br \/>\n console.log(this.props);<br \/>\n}<\/code><br \/>\nInstead, we pass the value of a prop to the super() function from the constructor():<br \/>\n<code>constructor(props) {<br \/>\n super(props);<br \/>\n console.log(this.props);<br \/>\n}<\/code><br \/>\nWhen you call a super() function, the parent class constructor is called, which is in the case of React is React.Component. <\/p>\n<p><strong>Step 2:<\/strong> Never call <strong><em>setState()<\/em><\/strong> inside the constructor()<br \/>\nThe best place to set the component&#8217;s initial state is in the constructor of your component. Instead of using <strong><em>setState()<\/em><\/strong> , you must directly set the initial state:<br \/>\n<code>constructor(props) {<br \/>\n super(props);<br \/>\n this.state = {<br \/>\n   name 'kapil',<br \/>\n   age: 22,<br \/>\n };<br \/>\n}<\/code><br \/>\nThe <em>constructor()<\/em> is the only place where you can assign the local state in this manner directly. You can use setState() somewhere else inside our component.<\/p>\n<p><strong>Step 3:<\/strong> Do not assign values from this.props to this.state<br \/>\nWhen setting the initial component state in the constructor, you should try to avoid setting values from the properties. We can do the following:<br \/>\n<code>constructor(props) {<br \/>\n super(props);<br \/>\n this.state = {<br \/>\n   name: props.name,<br \/>\n };<br \/>\n}<\/code><\/p>\n<p>Later, you wouldn&#8217;t be able to modify the property using setState(). Instead of assigning the property to the state directly, you can reference the property easily in your code by naming it to this.props.name.<\/p>\n<p><strong>Step 4:<\/strong> Bind events in one location.<br \/>\nWe can easily bind your event handlers in the constructor:<br \/>\n<code>constructor(props) {<br \/>\n super(props);<\/p>\n<p> this.state = {<br \/>\n   \/\/ Sets that initial state<br \/>\n };<br \/>\n \/\/ Our event handlers<br \/>\n this.onClick = this.onClick.bind(this);<br \/>\n this.onKeyUp = this.onKeyUp.bind(this);<br \/>\n \/\/ Rest Code<br \/>\n}<\/code><\/p>\n<h2>Creating a React Application:<\/h2>\n<p><strong>Step 1:<\/strong> Create a React application using the command below.<br \/>\n<code>npx create-react-app yourProjectName<\/code><\/p>\n<p><strong>Step 2:<\/strong> After creating your project folder, i.e., <em><strong>yourProjectName<\/strong><\/em>, move to it using the following command.<br \/>\n<code>cd yourProjectName<\/code><\/p>\n<p><strong>Project Structure:<\/strong> It will appear as shown below.<br \/>\n<img decoding=\"async\" src=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2023\/03\/project-structure.png\" alt=\"project-structure\"\/><\/p>\n<p><strong>Example:<\/strong> Now enter the code below into the App.js file. Our default component, App, is where we have written our code in this case. The following example explains the constructor demonstration.<\/p>\n<p><code>App.js<br \/>\nimport React, { Component } from 'react';<br \/>\nclass App extends Component {<br \/>\n  constructor(props) {<br \/>\n    \/\/ Calling super class constructor<br \/>\n    super(props);<br \/>\n    \/\/ Creating state<br \/>\n    this.state = {<br \/>\n      data: 'My name is User'<br \/>\n    }<br \/>\n    \/\/ Binding event handler<br \/>\n    this.handleEvent = this.handleEvent.bind(this);<br \/>\n  }<br \/>\n  handleEvent() {<br \/>\n    console.log(this.props);<br \/>\n  }<br \/>\n  render() {<br \/>\n    return (<br \/>\n      &lt;div><br \/>\n        &lt;input type=\"text\" value={this.state.data} \/><br \/>\n        &lt;br>&lt;\/br> &lt;br>&lt;\/br><br \/>\n        &lt;button onClick={this.handleEvent}>Please Click&lt;\/button><br \/>\n      &lt;\/div><br \/>\n    );<br \/>\n  }<br \/>\n}<br \/>\nexport default App;<\/code><\/p>\n<p><strong>Steps to Run the Application:<\/strong> Run the application  from the root directory of the project, using the following command<br \/>\n<code>npm start<\/code><\/p>\n<h3>Output:<\/h3>\n<p><img decoding=\"async\" src=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2023\/03\/output.gif\" alt=\"output\"\/><\/p>\n<p><small><em>jQuery presents a tree-like structure of all the elements on a webpage simplifying the syntax and further manipulating such elements. The <a href=\"https:\/\/www.studysection.com\/jquery-3.x-advanced\">jQuery Certification Exam<\/a> by StudySection will secure your fundamental knowledge and a basic understanding of jQuery as an asset to improve your skills.<\/em><\/small><\/p>\n","protected":false},"excerpt":{"rendered":"<p>A constructor() is a method that is launched whenever an object of that class is created. It can do initialization<\/p>\n","protected":false},"author":1,"featured_media":6534,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[789,641],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Constructor() method in ReactJS - StudySection Blog<\/title>\n<meta name=\"description\" content=\"A constructor() is a method that is launched whenever an object of that class is created. It can do initialization operations\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Constructor() method in ReactJS - StudySection Blog\" \/>\n<meta property=\"og:description\" content=\"A constructor() is a method that is launched whenever an object of that class is created. It can do initialization operations\" \/>\n<meta property=\"og:url\" content=\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Posts on famous people, innovations and educational topics\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/studysection\" \/>\n<meta property=\"article:published_time\" content=\"2023-03-20T04:55:35+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2023\/03\/ReactJS1-1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"300\" \/>\n\t<meta property=\"og:image:height\" content=\"200\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"admin-studysection-blog\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@studysection\" \/>\n<meta name=\"twitter:site\" content=\"@studysection\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin-studysection-blog\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/\"},\"author\":{\"name\":\"admin-studysection-blog\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\"},\"headline\":\"Constructor() method in ReactJS\",\"datePublished\":\"2023-03-20T04:55:35+00:00\",\"dateModified\":\"2023-03-20T04:55:35+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/\"},\"wordCount\":445,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"keywords\":[\"Constructor\",\"Reactjs\"],\"articleSection\":[\"Learn and Grow\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/\",\"url\":\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/\",\"name\":\"Constructor() method in ReactJS - StudySection Blog\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/#website\"},\"datePublished\":\"2023-03-20T04:55:35+00:00\",\"dateModified\":\"2023-03-20T04:55:35+00:00\",\"description\":\"A constructor() is a method that is launched whenever an object of that class is created. It can do initialization operations\",\"breadcrumb\":{\"@id\":\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/studysection.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Constructor() method in ReactJS\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/studysection.com\/blog\/#website\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"name\":\"Blog Posts on famous people, innovations and educational topics\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/studysection.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/studysection.com\/blog\/#organization\",\"name\":\"StudySection\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"contentUrl\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"width\":920,\"height\":440,\"caption\":\"StudySection\"},\"image\":{\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/studysection\",\"https:\/\/twitter.com\/studysection\",\"https:\/\/www.instagram.com\/study.section\/\",\"https:\/\/www.linkedin.com\/company\/studysection\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\",\"name\":\"admin-studysection-blog\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"caption\":\"admin-studysection-blog\"},\"url\":\"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Constructor() method in ReactJS - StudySection Blog","description":"A constructor() is a method that is launched whenever an object of that class is created. It can do initialization operations","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/","og_locale":"en_US","og_type":"article","og_title":"Constructor() method in ReactJS - StudySection Blog","og_description":"A constructor() is a method that is launched whenever an object of that class is created. It can do initialization operations","og_url":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/","og_site_name":"Blog Posts on famous people, innovations and educational topics","article_publisher":"https:\/\/www.facebook.com\/studysection","article_published_time":"2023-03-20T04:55:35+00:00","og_image":[{"width":300,"height":200,"url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2023\/03\/ReactJS1-1.png","type":"image\/png"}],"author":"admin-studysection-blog","twitter_card":"summary_large_image","twitter_creator":"@studysection","twitter_site":"@studysection","twitter_misc":{"Written by":"admin-studysection-blog"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#article","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/"},"author":{"name":"admin-studysection-blog","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402"},"headline":"Constructor() method in ReactJS","datePublished":"2023-03-20T04:55:35+00:00","dateModified":"2023-03-20T04:55:35+00:00","mainEntityOfPage":{"@id":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/"},"wordCount":445,"commentCount":0,"publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"keywords":["Constructor","Reactjs"],"articleSection":["Learn and Grow"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/","url":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/","name":"Constructor() method in ReactJS - StudySection Blog","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/#website"},"datePublished":"2023-03-20T04:55:35+00:00","dateModified":"2023-03-20T04:55:35+00:00","description":"A constructor() is a method that is launched whenever an object of that class is created. It can do initialization operations","breadcrumb":{"@id":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/studysection.com\/blog\/constructor-method-in-reactjs\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/studysection.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Constructor() method in ReactJS"}]},{"@type":"WebSite","@id":"https:\/\/studysection.com\/blog\/#website","url":"https:\/\/studysection.com\/blog\/","name":"Blog Posts on famous people, innovations and educational topics","description":"","publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/studysection.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/studysection.com\/blog\/#organization","name":"StudySection","url":"https:\/\/studysection.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","contentUrl":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","width":920,"height":440,"caption":"StudySection"},"image":{"@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/studysection","https:\/\/twitter.com\/studysection","https:\/\/www.instagram.com\/study.section\/","https:\/\/www.linkedin.com\/company\/studysection"]},{"@type":"Person","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402","name":"admin-studysection-blog","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","caption":"admin-studysection-blog"},"url":"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/"}]}},"views":171,"_links":{"self":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/6533"}],"collection":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/comments?post=6533"}],"version-history":[{"count":3,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/6533\/revisions"}],"predecessor-version":[{"id":6797,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/6533\/revisions\/6797"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media\/6534"}],"wp:attachment":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media?parent=6533"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/categories?post=6533"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/tags?post=6533"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}