Sunday, 5 January 2020

Introduction to component in ReactJs


Component

It is one of the core building blocks of react. We can say that any application build by multiple parts or pieces like (Sidebar, menu-bar, navigation-bar, search-bar, content, etc..) called as Components.

Component in react basically returns a piece of JSX code which tells about what should be render on the screen. In react we have two types of components.


1) Functional component

       It is simply JavaScript function in react with JSX code. these function may or may not             receive the data as parameter.

Functional component are not aware about the other component.

function Funccomponent()
{
    return <h1>Welcome Message!</h1>;
}


2) Class component

class component can work within other component. Data can pass through one component to other component. we can use JS ES6 class to create class based component.

import React from 'react';

class MyApp extends React.Component {
   render() {
      return (
         <div>
            <Header/>
            <Content/>
         </div>
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>This is Header</h1>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <h2>Content</h2>
            <p>This is content text!!!</p>
         </div>
      );
   }
}
export default App;

Rendering Components
To render a component in React we can initialize an element with a user-defined component and pass this element as the first parameter to ReactDOM.render() or directly pass the component as first argument to the ReactDOM.render() method.
Below syntax shows how to initialize a component to an element:
const elementName = <ComponentName />;
In the above syntax the ComponentName is the name of the user-defined component.
Note: The name of a component should always start with a capital letter. This is done to differentiate a component tag with html tags.



No comments:

Post a Comment