Home »
React JS
Introduction to React JS Components
React JS Components Introduction: In this tutorial, we are going to learn about the Introduction to the React JS components.
Submitted by Godwill Tetah, on November 21, 2019
In this article, I will help you walk through the process of creating or working with React JS components for your projects.
As it's always said, everything in React JS is all about components.
I suggest reviewing some recent articles that will be of help too.
what are components?
In React JS, components are like functions in vanilla Js (the basic JavaScript for all browsers) which help us perform some tasks.
In React JS, components can be used to render an HTML code to an HTML element (like a div) or root node.
Example:
Class App extends React.Component
render () {
return (
<h1> hello react noobs! </h2>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
Components are reusable blocks of code just like JavaScript functions that can be reused over and over.
From the example above, you can see that I created a class called App which is passed as the first parameter (using the syntax <App />) in the ReactDOM.render() method.
The component above is called a class component because it makes use of ES6 classes or uses the word class to create the component.
The component above can be added in any piece of code or another component by using the component's name in the syntax : < ... /> as seen in the example above.
Syntax:
Class yourclassname extends React.Component
render () {
return (
// your code enters here
)
}
ReactDOM.render(<.../>, document.getElementById('root'));
Your class component must include render() and return(). The return() must have one parent element.
Function Components
There is another type of component called the function component or the simple component. The name was given as such because it doesn't use the class keyword to create the component and also because it's more like a function in vanilla JS in syntax.
Example:
function App () {
return (
<h2> Hello React Noobs! </h2>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
You can equally write same code using arrow functions,
const x App = ( ) => {
return <h2> Hello world </h2> ;
}
ReactDOM.render(<App />, document.getElementById('root'));
From the code above, you can see the function component has just the return() statement without the render().
Also, note that: If the content of return() is only one line, you can remove the parenthesis.
Thanks for coding with me! See you @ the next article. Feel free to drop a comment or question.