React components

React components

Components

React components are normal Javascript functions that can stand alone, return HTML, and be reused across your code.

There are two types of React Components

  • Class components

  • Functional Components

class Flower extends React.Component {
  render() {
    return <h2>Flowers are in bloom </h2>;
  }
}

Functional Components

Functional components are preferred to the class component because it’s less complex, as it doesn't require life-cycle methods, this binding and state.

How can functions be reused?

It can be reused using props (which stand for properties)!
Props are simply Javascript objects that can be passed as arguments to functions. This can be used to transfer the values of components across different parts of our code.

Props can also be used like HTML attributes, just like below:

Example

const firstElement = <Flower specie="Lily" />;
function Flowers(props) {
  return <h2>I am a { props.specie }!</h2>;
}

Props can also be used to transfer data, just as below:

Example

function Flowers(props) {
  return <h2>I am a { props.spiece }!</h2>;
}

function Yard() {
  return (
    <>
      <h1>Guess what spiece of flower I planted in the yard?</h1>
      <Flower spiece="Lily" />
    </>
  );
}

Or

We can create a variable for our props and then reuse them.


function Flowers(props) {
  return <h2>I am a { props.spiece }!</h2>;
}
function Yard() {
const spec = 'Lily';
  return (
    <>
      <h1>Guess what spiece of flower I planted in the yard?</h1>
      <Flowers spiece={spec} />
    </>
  );
}

Components as objects

function Flowers(props) {
  return <h2>I am a { props.spiece.spec }!</h2>;
}

function Yard() {
  const flowerInfo = { name: "Lily", spec: "Madonna Lily" };
  return (
    <>
      <h1>Guess what spiece of flower I planted in the yard?</h1>
      <Flowers specie={ flowerInfo } />
    </>
  );
}

Components can also be written in other components, right?
It can be done this way:

import React from 'react';
import Flowers from './Flower.jsx';

function Home() {
<Flowers />
// here the Flowers component is written in the Home component 
}

To keep your code clean and readable, it is advised that you separate your components into separate files.

Example:

This helps with reusability. To reuse a component, we import the file.

Just like below:

import React from 'react';
import Flowers from './Flower.jsx';

function Home() {
<Flowers />
// here the Flowers component is written in the Home component 
}

It should be noted that when importing, the ‘.js or jsx’ must be in small letters.

That will be all for now!
The next article will be on 'Rendering in React'.

Let me know what you think about this article; like, share, and comment!