Read it in 12 Mins
Is by Doing
React is one of the most popular JavaScript libraries for building user interfaces. If you are thinking of getting into front-end development or web development, then learning React will be a good way to start.
In this blog you are going to learn basic concepts in React such as components and their types, JSX syntax and props. Let’s start with JSX.
Soon after installing a React project, if you open App.js in your favourite editor you will observe that a JavaScript function returns some HTML code. It is called JSX(JavaScript XML).
This is a valid and widely accepted syntax extension to JavaScript. It is recommended to use it to describe what the UI should look like.
In frontend-related projects, we keep HTML, CSS, and JavaScript code in separate files. However, React works a bit differently. In React we don’t create HTML files because JSX allows us to write HTML and JavaScript combined in the same file. But CSS needs to be separated to a new file as shown in the figure (App.css).
We can assign HTML tags to JavaScript variables:
Code:
var name = <p>React</p>;
Here, we have assigned HTML to name variable.
You can return HTML conditionally (such as if-else cases):
Code:
function App() { var condition = true; if (condition) { return <p>true</p>; } else { return <p>false</p>; } }
Read more about JSX here
There are some differences as compared to HTML:
Code:
return (
<div>
<p>Hello</p>
<p>World</p>
</div>
)
A component is an independent, reusable bit of code which divides the UI into smaller pieces. For example, if we were building the UI of React website using Reactjs we can break its UI into smaller parts as shown in the figure.
Instead of building the whole UI under one single file like HTML, we can divide all the sections (marked with red) into smaller independent pieces. In other words, these are components. Each component will go into its own JavaScript file.
In React we have two types of components: functional and class. Let's look at each type of component in more detail. But before that, let’s gain an understanding of extraction of components.
As you know, everything in React is a component. Each component returns some HTML but we can return only a single HTML element; inside which we can write many child elements as we have seen in the examples. Instead of writing all the code in a single file we can split our app into multiple components.
We can then extract the code which is used for some unique purpose into a separate component and use that component wherever we want in our app, instead of rewriting and duplicating the code.
In the following examples we have already extracted components into
Now I can use both the components in any place inside the app without duplicating the code. This is called extracting and reusing components
The first, most important and recommended component type in React is a functional component. A functional component is basically a JavaScript function that returns a React element (JSX).
Functional components start with function keyword.
Code:
function HelloWorld() { return <h1>Hello world</h1>; }
Alternatively, you can also create a functional component with the arrow function syntax(ES6).
Code:
const HelloWorld = () => { return <h1>Hello world</h1>; };
You need to export the component in order to use it somewhere else.
Code:
function HelloWorld() { return <h1>Hello World</h1>; } export default HelloWorld;
As HelloWorld is exported here, we can import this component into another file (which will be App.js in our case) and use it as shown below.
Code:
import HelloWorld from "./HelloWorld"; const App = () => { return ( <div className="App"> <header className="App-header"> <HelloWorld /> </header> </div> ); }; export default App;
In short, a functional component is a JavaScript function or ES6 function which takes props as arguments and returns a JSX.
Components should always start with a capital letter.
Another type of component is a class component. Just as we have functions, we also have classes in JavaScript. Class components are ES6 classes that return JSX. The same HelloWorld function can be converted to a class component.
Class components start with class keyword that extends the Component constructor from React and has a render method which returns a JSX.
Code:
class HelloWorld extends React.Component { render() { return <h1>Hello World</h1>; } }
Apart from returning the JSX, sometimes we have a situation where we need to manage some data inside the components; which makes the components more dynamic and makes our application faster and more user friendly. This data is called state.
We used to use class components in order to manage the state. In the older versions of React (before version 16.8), it was not possible to use state inside functional components.
Apart from managing the state we use class components to perform some additional operations, like life-cycle methods.
To summarise, a class component is an ES6 class which extends a React.Component. It uses render method to return a JSX. It accepts props (inside constructor) if necessary.
This has changed with the introduction of React Hooks, and now we can also manage state and perform life cycle methods inside functional components with hooks.
A Prop is a way that components communicate. React uses props to transfer data from one component to another component.
But remember that props only transport data in a one-way flow (only from parent to child components). It is not possible for props to pass data from a child to parent, or to components at the same level.
Now let’s go back to our App component and pass props from an App to its child (HelloWorld.js in our case).
First, we need to define a prop on the HelloWorld Component and assign a value to it.
Code:
import HelloWorld from "./HelloWorld"; const App = () => { return ( <div className="App"> <header className="App-header"> <HelloWorld title="Hello World" /> </header> </div> ); };
Here we passed title as a prop to HelloWorld component and gave it a value of “Hello World” which is a string.
Props are custom values and they also make components more dynamic.
Since the HelloWorld component is the child here, we need to define props on its parent (App), so we can pass the values and get the result simply by accessing the prop title in the HelloWorld component as shown below.
Code:
function HelloWorld(props) { return <h1>{props.title}</h1>; } export default HelloWorld;
If you save the files and start the app and look at the browser, you will find HelloWorld on the screen as shown below.
Now we have made the HelloWorld component more dynamic by passing our title as a prop to the component. Let’s see how we made it dynamic.
We can use HelloWorld component more than once in our App component but with a different value than our title prop, as shown below.
Code:
import HelloWorld from "./HelloWorld"; const App = () => { return ( <div className="App"> <header className="App-header"> <HelloWorld title="Hello World" /> <HelloWorld title="Hello India" /> <HelloWorld title="Hello America" /> <HelloWorld title="Hello China" /> </header> </div> ); };
Now if you save the files and reload the browser, the screen is shown as below.
Now we are outputting different titles from the same component (HelloWorld.js) which makes the component Dynamic.
We can do the same using class components as well. Now let’s change HelloWorld.js into a class component which accepts props. We can achieve that by changing the code as shown below.
Code:
import React from "react"; class HelloWorld extends React.Component { constructor(props) { super(props); } render() { return <h1>{this.props.title}</h1>; } } export default HelloWorld;
Now when you save it, you will find no change in the output you see on the screen. But this time we are using class components.
Note: We can access props directly upon this keyword in class components (this.props.title) and there is no need of a constructor. It has been added just for the reference, and we will learn about it next.
It's important to note that props are Read Only; that is, we cannot change the value of the props inside the child components. We can only use the props as shown in the example without changing their value.
In JavaScript the constructor is a method used to initialize an object's state in a class. It is automatically called during the creation of an object in a class.
The concept of a constructor is the same in React. The constructor in a React component is called before the component is mounted. We use that to define a state object inside a class component.
We can change our existing class component to use state and props by changing the code as shown below.
Code:
import React from "react"; class HelloWorld extends React.Component { constructor(props) { super(props); this.state = { header: props.title, }; } render() { return <h1>{this.state.header}</h1>; } }
Now if you save you will find no change in the output you see on the screen. But this time we are using state and props inside the class component.
Sometimes when working with React, people get carried away and create too many components. This leads to deeply nested structures which make it difficult to pass props all the way down. This can be solved to an extent by using 2 techniques.
In React, a composition is a pattern of the component model. It's how we build components from other components, of varying complexity and specialization through props. Depending on how generalized these components are, they can be used in building many other components.
The Provider component which is provided by React Redux and Context API in React Hooks is the best example of a Composition.
For Example:
Here we have App.js which passes title and description as props to HelloWorld.js component.
Code:
import "./App.css"; import HelloWorld from "./HelloWorld"; const App = () => { return ( <div className="App"> <header className="App-header"> <HelloWorld title="Hello World" description="Getting started with react" /> </header> </div> ); }; export default App;
HelloWorld.js uses title prop but it does not use the description; instead, it just sends it as a prop to its child component, that is Description.js.
import Description from "./Description"; const HelloWorld = (props) => { return ( <div> <h1>{props.title}</h1> <Description description={props.description} /> </div> ); }; export default HelloWorld;
Description.js actually uses a description which is passed from App.js. This is called prop drilling.
This can be avoided by creating a context for our App and composing our app with the Provider component, which is provided by createContext hook, and then passing our required data as an object to the provider component as shown below.
Code:
import { createContext } from "react"; import "./App.css"; import HelloWorld from "./HelloWorld"; export const Context = createContext(); const App = () => { return ( <Context.Provider value={{ title: "Hello World", description: "Getting started with react", }} > <div className="App"> <header className="App-header"> <HelloWorld /> </header> </div> </Context.Provider> ); }; export default App;
Now we can pull out our data from the context using a useContext hook, and use the required data within the components instead of passing them as props, as shown below.
Example: In HelloWorld.js we pull out the title as we only need that in this component.
Code:
import { useContext } from "react"; import Description from "./Description"; import { Context } from "./App"; const HelloWorld = () => { const { title } = useContext(Context); return ( <div> <h1>{title}</h1> <Description /> </div> ); }; export default HelloWorld;
Example:In HelloWorld.js we pull out the description as we only need that in this component.
Code:
import { useContext } from "react"; import { Context } from "./App"; const Description = (pops) => { const { description } = useContext(Context); return <p>{description}</p>; }; export default Description;
If you observe in the above code, the components are not taking any props but are still getting access to all the data, as we have Composed our App component with the Provider component from context. This helps in less prop drilling, and cleaner and readable code.
Higher Order Components:
Higher Order Components are JavaScript functions used for adding additional functionalities to the existing component. These functions are pure, which means they are receiving data and returning values according to that data. If the data changes, higher order functions are re-run with different data inputs.
A Higher Order Component (HOC) is wrapping around a "normal" component and providing additional data input. It is actually a function that takes one component and returns another component that wraps the original one.
Now let's try to rewrite the App we used all this time using Higher Order Components.
Let's create a Higher Order Component MyHOC.js which takes a component and returns a component as shown below.
Code:
const MyHOC = (Component) => (props) => { const description = "Getting started with react"; return <Component description={description} {...props} />; }; export default MyHOC;
Here our Higher Order Component returns a component. However, by enhancing its properties in this case we pass additional data (description) as a prop, along with the props which are passed to the component.
Now we can pass our HelloWorld.js to this Higher Order Component as shown below.
Code:
import MyHOC from "./MyHOC"; const HelloWorld = (props) => { return ( <div> <h1>{props.title}</h1> <p>{props.description}</p> </div> ); }; export default MyHOC(HelloWorld);
Here we wrap the Helloworld.js within the Higher Order Component that we just created; but we can use the description prop passed by MyHOC component which is a Higher Order Component. We can avoid prop drilling, and add many other properties to other components using Higher Order Components.
What have you learnt?
We have learnt about the two types of components in React; functional and class components. We learnt about extraction of components and how to reuse the components. After that, we went on to learn about props: how to pass them and use them inside the child components. We understood what prop drilling is, and have seen how to avoid prop drilling by using composing method and Higher Order Components.
If you are aspiring to be a React developer, these are basic concepts that you should thoroughly understand, before moving on to more complex code.
Name | Date | Fee | Know more |
---|