Home

React Components

React applications are made out of components.
A component is a small, reusable chunk of code that is responsible for one job.
That job is often to render some HTML.

This code example will create and render a new React component:

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponentClass extends React.Component {
   render() {
      return <h1>Hello world</h1>
   }
};

ReactDOM.render(
   <MyComponentClass />,
   document.getElementById('app')
);


React Library

The following 2 lines of code that go at the top of the form are necessary...

import React from 'react';
import ReactDOM from 'react-dom';


Both of the above lines of code import JavaScript objects.
In both lines, the imported object contains React-related methods.

The methods imported from 'react' don’t deal with the DOM at all - They don’t engage directly with anything that isn’t part of React.

And the methods imported from 'react-dom' are used to interact with the DOM.

Top

import React from 'react';

This line of code creates an object named React which contains methods necessary in order to use the React Library.

One of the methods contained in this object is React.component which is required by JSX (and called automatically by JSX).
Therefore we MUST have this line of code before JSX will work.

import ReactDOM from 'react-dom';

The methods imported from 'react-dom' are meant for interacting with the DOM, eg
ReactDom.render()

Top

Create a Component Class

React component is a small, reusable chunk of code that is responsible for one job, which often involves rendering HTML.

We can use a JavaScript class to define a new React component.
We can also define components with JavaScript functions.

Dealing with class components first.


All class components will have some methods and properties in common.
Rather than rewriting those same properties over and over again every time, we extend the Component class from the React library.
This way, we can use code that we import from the React library, without having to write it over and over again ourselves.

React.Component is a JavaScript class.
To create your own component class, you must subclass React.Component.
You can do this, for example, by...
class YourComponentNameGoesHere extends React.Component {}

In this scenario YourComponentNameGoesHere is a subclass of React.Component


An example can be seen here...

import React from 'react';
import ReactDOM from 'react-dom';

class MyComponentClass extends React.Component {
   render() {
      return (<h1>Hello world</h1>)
   }
};

ReactDOM.render(
   <MyComponentClass />,
   document.getElementById('app')
);


NOTE
Class names should start with a capital letter (known as UpperCamelCase).
This is the case for Javascript coding but in the case of React class names MUST start with a capital letter.

ALSO NOTE
The line of code
return (<h1>Hello world</h1>)
has round brackets '( )' but if you are only returning 1 element (the h1 element) then the ( )'s can be omitted.


Make a React Component

To make a React component, you write a JSX element.
Instead of naming your JSX element something like h1 or div this time we give it the same name as the component class, eg...
<MyComponentClass />

So when you want to render your class you would say...

ReactDOM.render(
   <MyComponentClass />,
   document.getElementById('app')
);


Basically you are pretending it is a (self closing) JavaScript Tag and rendering it.
You will be putting the name inside the < /> (not forgetting the / to close it).




Another Example...

import React from 'react';
import ReactDOM from 'react-dom';

const redPanda = {
  src: 'Images/Red_Panda.jpg',
  alt: 'Red Panda',
  width:  '200px'
};

class RedPanda extends React.Component {
  render() {
    return (
      <div>
        <h1>Cute Red Panda</h1>
        <img 
          src={redPanda.src}
          alt={redPanda.alt}
          width={redPanda.width} />
      </div>
    );
  }
}

ReactDOM.render(
  <RedPanda />,
  document.getElementById('app')
);


This example creates an object (redPanda) that has properties (src, alt & width) associated with it.

That objects properties are then used inside the RedPanda class in the render() method.
NOTE the curly brackets { }'s around the redPanda object to tell JSX it is to use the object, otherwise it will just treat it as TEXT and not display the actual value of the object.property.

ALSO NOTE In the ReactDOM.render()the class name RedPanda is listed inside < /> (<RedPanda />) as it is treated like a JavaScript self-closing TAG/ELEMENT (eg <img />) and must be coded like that.

Top

Adding Logic to a Render Function

A render() function must have a return statement.
A render() function can also be a fine place to put simple calculations that need to happen right before a component renders.

Any simple calculations/logic MUST be placed AFTER the RENDER() and BEFORE the RETURN command. Eg...

class Random extends React.Component {
   render()
{
       // First, some logic that must happen
      // before rendering:

      const n = Math.floor(Math.random() * 10 + 1);
       // Next, a return statement
      // using that logic (must be inside {}'s):

       return (
         <h1>The number is {n}!</h1>
      );
   }
}


And remember, when you call the routine to render the class
In the ReactDOM.render()the class name Friend is listed inside < /> (<Friend />) as it is treated like a self-closing JavaScript TAG/ELEMENT (eg <img />) and must be coded like that.

ReactDOM.render(
   <Friend />,
   document.getElementById('app')
);


Adding Logic Part 2

Another Example...

import React from 'react';
import ReactDOM from 'react-dom';

const apocalypse = false;

class TodaysPlan extends React.Component {
  render() {
    let task;
    if (!apocalypse) {
      task = 'learn React.js'
    } else {
      task = 'run around'
    }

    return <h1>Today I am going to {task}!</h1>
  }
}

ReactDOM.render(
    <TodaysPlan />,
	document.getElementById('app')
);

Top

Methods in Classes

render() is a method inside the class.
You can also create other methods (like functions() ) and then call them inside the render() method (using the this. command).

Because the functions() are being called by the render() method they need to go above the render method inside of the class, eg...

class MyClass extends React.Component {
    myFunc() {
      alert('Stop it. Stop hovering.');
   }


   render() {
      return (
         <div onClick={this.myFunc}></div>
      );
   }
}


NOTE
You do not use the ()'s when calling the function (but you do need them when creating the function)... {this.myFunc} and NOT {this.myFunc()}.


Also Note...
this. is not used when referring to a property/method/function that is created outside of the class (see Adding Logic Part 2 example, above. The property apocalypse is outside the class).


Getters in Classes

Similar to other methods...
You can also create other methods (like Getters ) and then call them inside the render() method (using the this. command).

Because the Getters are being called by the render() method they need to go above the render method inside of the class, eg...

class IceCreamGuy extends React.Component {
    get food() {
      return 'ice cream';
   }


   render() {
      return (
         <h1>I like {this.food}.</h1>
      );
   }
}


NOTE
You do not use the ()'s when calling the getter (but you do need them when creating the getter)... {this.food} and NOT {this.food()}.


Top

Setting Properties to JSX

Variables (or properties) can be set to JSX and be passed to render, eg...

const myProp = <h1>This is a h1 tag</h1>;

or

const myProp = (
   <div>
      <h1>This is a h1 tag</h1>
      <h2>Followed by h2</h2>
   </div>
);

NOTE
If you only have ONE tag to saved to the property then you do not need to specify any opening/closing parentheses, ().
BUT if you have TWO OR MORE then you must include ()'s.
I think I like to include them anyway whilst learning.

Top

Example Code...

Authorization Form

Scenario
A client just called you to say that they love their new website!
There’s only one problem: they don’t like how their contact page displays their personal information for all to see.

They’ve asked you to hide their website’s contact page behind a password form.



You can read about .bind(this) in w3schools React Events page Here

NOTE If you must use regular functions instead of arrow functions you have to bind this to the component instance using the bind() method.
Without the binding, the this keyword would return undefined.


Also, it's worth taking a look at another document about binding .this() Here

Example...

import React from 'react';
import ReactDOM from 'react-dom';

class Contact extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      password: 'swordfish',
      authorized: false
    };
    this.authorize = this.authorize.bind(this);
  }

  authorize(e) {
    const password = e.target.querySelector(
      'input[type="password"]').value;
    const auth = password == this.state.password;
    this.setState({
      authorized: auth
    });
  }

  render() {
    let contact = "Contact";
    if (!this.state.authorized) {
      contact = "Enter the Password";
    }

    const login = (
        <form onSubmit={this.authorize} action="#">
            <input type="password" placeholder="password" />
            <input type="submit" />
        </form>);
    
    const contactInfo = (
      <ul>
        <li>
          client@example.com
        </li>
        <li>
          555.555.5555
        </li>
      </ul>
    );

    return (
      <div id="authorization">
         <h1>{contact}</h1>
         {this.state.authorized ? contactInfo : login};
      </div>
    );
  }
}

ReactDOM.render(
            <Contact />, 
  document.getElementById('app')
);
Top