DEV Community

Bipin singh
Bipin singh

Posted on

How to create simple component in React

React is a javascript library which makes it easy to create an awesome ui.

Component is a basic building block of a every react project. Let's understand how we can create a simple hello world component in react.

Component can be created in two ways in react.

  1. Functional component
  2. Class component

Let's first understand how to create a component using class.

Class component

  • Every react component start with simple import statement.
Import React from react
  • We have to create a class and have to extends React.component into it.
class HelloWorld extends React.component {

}

Note: First letter of the component in react should be capital letter.

  • We have to implement render function to render ui into Dom(document object model).
render() {
  return <h1>Hello world</h1>;
}
  • To render a component in dom we have to import react-dom
import ReactDOM from 'react-dom'
  • Complete code:
Import React from 'react';
import ReactDOM from 'react-dom';

class HelloWorld extends React.component {
 render() {
  return <h1>Hello world</h1>;
 }
}
ReactDOM.render(<HelloWorld />, document.getElementById("root"));

Functional component

  • Every react component start with simple import statement.
Import React from react
  • We have to create a function
function HelloWorld {

}
  • We have to return from the function to render ui into Dom(document object model).
return <h1>Hello world</h1>;
  • To render a component in dom we have to import react-dom
import ReactDOM from 'react-dom'
  • Complete code:
Import React from 'react';
import ReactDOM from 'react-dom';

class HelloWorld {
  return <h1>Hello world</h1>;
}
ReactDOM.render(<HelloWorld />, document.getElementById("root"));

Hope this will be helpful for all of you.
Keep Learning.

Top comments (0)