I recommend you subscribe to our newsletter, YouTube channel and frequently visit our blog to get more awesome stuff in your programming language or framework.
Now let’s get started…
What are components?
In React JS, a component can be likened to a function, but returns HTML elements.
Just like functions, components can be re-used.
Components are pieces which form the UI of an application. For example, you might have a header component, a footer component and sidebar component.
Similarly, as regular vanilla JavaScript functions accepts parameters or arguments, React JS components equally accept properties or props which we will cover in our next tutorial.
How do we create components?
There are actually 2 categories of components;
- Class components and
- Functional components
Below is an example of a class component;
class Greetings extends React.Component {
render() {returnHello, world
; } }
The class component above begins with the keyword class and has a render function which returns an HTML element.
Below is a functional component:
function Greetings (){
return Hello, world
;
}
The Greetings components above do the same thing. But you might be asking whether it is better to use class or functional components?
Well, each have their advantages and limitations.
Rule : Start all component names with Capital letters, be it functional or class component.
How do we render these components?
The render function accepts two arguments which are the code to be rendered which is usually in the components and the container (root node) which will hold the html elements or code.
So the component is rendered by simply adding the name of the component like a tag as the first argument of the render () before the root node.
In your create-react-app boiler-plate, edit the index.js file as follows;
import React from 'react';
import ReactDOM from 'react-dom';
class Greetings extends React.Component {
render() {
return Hello, world
;
}
}
ReactDOM.render(, document.getElementById('root'));
Looking at the code above, you see how I rendered the greetings component;
<Greetings />
OUTPUT
How About Components In External File?
To create a component in an external file, you should create a file with the .js extension and then import any modules or features you might want to import, type your component and them export.
After doing so, import the external js file component into your main app and then use. Below is a typical example.
Lets create a file called Test.js and type our code (component);
Test.js
Remember, the function name or component name should always begin with a capital letter. Notice also how we exported the component with same name as function name.
Now let’s import, render and see the output.
index.js
OUTPUT
Thanks.
See you in the next tutorial.
Comments
Post a Comment
Please do not enter any spam link in the comment box.