Components in React can be created in 2 ways:

  1. With a function
  2. With a ES6 class

Creating component with a function

import React from 'react';

const SearchBar = () => {
  return <input />
};

export default SearchBar;

This is a component which renders a input text field.

This type of a component is called as functional component, because the component is literally a function. The function may take an argument and returns some JSX.

There is another type of componet in React, which is called as class component. This is essentially helpful when we want to have the component to keep some sort of record keeping. Some ability like having aware of itself and what happened to itself since when it got rendered.

Creating component with a class

In the above example of text field, user will type something into text field, so the component should be aware of what the user typed in, and what to do with it. So, we need to create a class based component here.

import React from 'react';

class SearchBar extends React.Component {
  render() {
    return <input />;
  }
}

export default SearchBar;
  • The class should extend React.Component class. This gives our class access to bunch of functionalities from React.Component class.
  • Every class based component in React MUST have a render() method, which will return the JSX.

The above class can also be written as:

import React, { Component } from 'react';

class SearchBar extends Component {
  render() {
    return <input />;
  }
}

export default SearchBar;

The below line

import React, { Component } from 'react';

means "Import React, and pull off the property "Component", and assign it to constant "Component" ". It is exactly identical to:

const Component = React.Component;

results matching ""

    No results matching ""