Thursday 4 March 2021

Part 5 : React Component

In this and few upcoming articles I will discuss on react component. Open Index.js file from hellosample project created in previous article.
Below highlighted at line number 9 ‘App’ is nothing but alias name of reference of JavaScript file. To reference App.js in Index.js file import keyword is used, for more details check piece of code written in line number 4. Basically App.js contains react component and that component is referred in index.js file. Index.js file pass on react component to div element written in line number 11.
Open command prompt and navigate to project folder. In my case name of project is hellosample and I have to navigate till hellosample folder to run react application. Type command ‘npm start’ and press enter. It will launch react app in browser window. Now come back again in Index.js file and replace with h2 tag with text inside h2 tag ‘Hello World’ from line number 9 and refresh browser window.
Let’s modify code shown in below screen, you can create more than one reactDom.render method.
You can also pass HTML here but it is not recommended. I provided hardcoded HTML which won't reuse in future and it is not react. React is all about component as we discussed. Let’s undo changes and replace h2 tag again with App. And also delete second reactDom.render method created for Hello Word2.
Open App.js file shown below.
JavaScript function with name App contains component, as we discussed component is HTML code written inside JavaScript function or class. If you want other JavaScript file to access component from App.js file, need to provide permission with export keyword written on line number 25. Remember HTML inside JavaScript file is not actual html its virtual DOM/Html and JavaScript support html syntax in JavaScript files with the help of JSX. Please refer first two articles for more details.
You can also write JavaScript function and avoid HTML syntax for building react component. Let’s see in action below.
Line number 11 highlighted which provide div element with message. Now I want to apply CSS file for created div and header tag inside div element.
If you noticed, I have pass React.createElement method as third parameter for main/parent React.createElement method. Based of HTML nesting function call nesting also change. For now, we have simple HTML like Div and header inside div later may be complex HTML like Div and table inside div which is difficult to handle or complex to write using createElement method. Better use JSX which provide HTML syntax inside JavaScript and easy to understand and write. There are some restrictions in JSX which I will walk you through once we reach to that topic. In above screen CSS class is written with className=’App’ (line number 7 and 11) as class is reserved for JavaScript class keyword and name of CSS class in JSX written as className.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home