Unit 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

1

UNIT-2
What is React JSX ?
JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript. It
helps us to write HTML in JavaScript and forms the basis of React Development. Using
JSX is not compulsory but it is highly recommended for programming in React as it makes
the development process easier as the code becomes easy to write and read.
JSX creates an element in React that gets rendered in the UI. It is transformed into
JavaScript functions by the compiler at runtime. Error handling and warnings become
easier to handle when using JSX
Sample JSX code:
const ele = <h1>This is sample JSX</h1>;

Why JSX ?
 It is faster than normal JavaScript as it performs optimizations while translating to
regular JavaScript.
 It makes it easier for us to create templates.
 Instead of separating the markup and logic in separate files, React uses components for
this purpose. We will learn about components in detail in further articles.
 As JSX is an expression, we can use it inside of if statements and for loops, assign it to
variables, accept it as arguments, or return it from functions.
Expressions in JSX
In React we are allowed to use normal JavaScript expressions with JSX. To embed
any JavaScript expression in a piece of code written in JSX we will have to wrap that
expression in curly braces {}. The below example specifies a basic use of JavaScript
Expression in React.
Syntax:
const example = "JSX"
const ele = <div>This component uses {example} </div>
Example: This example wraps the JSX code in curly braces
 javascript
// Filename - App.js
import React from "react";
const name = "Learner";
const element = (
<h1>
Hello,
{name}.Welcome to GeeksforGeeks.
</h1>
);

ReactDOM.render(element, document.getElementById("root"));
Output:

ReactJS JSX
2

In the above program, we have embedded the javascript expression const name =
“Learner”; in our JSX code. We can use conditional statements instead of if-else
statements in JSX.

Attributes in JSX
JSX allows us to use attributes with the HTML elements just like we do with normal
HTML. But instead of the normal naming convention of HTML, JSX uses the camelcase
convention for attributes.&
 The change of class attribute to className:The class in HTML
becomes className in JSX. The main reason behind this is that some attribute names in
HTML like ‘class‘ are reserved keywords in JavaScript. So, in order to avoid this
problem, JSX uses the camel case naming convention for attributes.
 Creation of custom attributes:We can also use custom attributes in JSX. For custom
attributes, the names of such attributes should be prefixed by data-* attribute.
Specifying attribute values :
JSX allows us to specify attribute values in two ways:
 As for string literals: We can specify the values of attributes as hard-coded strings
using quotes:
const ele = <h1 className = "firstAttribute">Hello!</h1>;
 As expressions: We can specify attributes as expressions using curly braces {}:
const ele = <h1 className = {varName}>Hello!</h1>;
Wrapping elements or Children in JSX
Consider a situation where you want to render multiple tags at a time. To do this we
need to wrap all of these tags under a parent tag and then render this parent element to the
HTML. All the subtags are called child tags or children of this parent element.
Note: JSX will throw an error if the HTML is not correct or if there are multiple
child elements without a parent element.
Comments in JSX :
JSX allows us to use comments as it allows us to use JavaScript expressions.
Comments in JSX begin with /* and ends with */. We can add comments in JSX by
wrapping them in curly braces {} just like we did in the case of expressions. The below
example shows how to add comments in JSX:
 Javascript
// Filename - App.js
import React from "react";
import ReactDOM from "react-dom";
const element = (
<div>
<h1>Hello World !{/*This is a comment*/}</h1>
</div>
);

ReactDOM.render(element, document.getElementById("root"));
Output:
3

Converting HTML to JSX


Let us take the following HTML Code and Convert it into JSX
 HTML
<!DOCTYPE html>
<html>
<head>
<title>Basic Web Page</title>
</head>
<body>
<h1>Welcome to GeeksforGeeks</h1>
<p>A computer science portal for geeks</p>
</body>

</html>
The Converted JSX Code will look like:
 Javascript
<>
<title>Basic Web Page</title>
<h1>Welcome to GeeksforGeeks</h1>
<p>A computer science portal for geeks</p>
</>
Rules to Write JSX
 Always return a single Root Element: When there are multiple elements in a
component and you want to return all of them wrap them inside a single component
 Close all the tags: When we write tags in HTML some of them are self closing like
the <img> tag but JSX requires us to close all of them so image tag will be represented
as <img />
 Use camelCase convention wherever possible: When writing JSX if we want to give
class to a tag we have to use the className attribute which follows camelCase
convention.

What are React JS Components ?


A Component is one of the core building blocks of React. In other words, we can
say that every application you will develop in React will be made up of pieces called
components. Components make the task of building UIs much easier. You can see a UI
broken down into multiple individual pieces called components and work on them
independently and merge them all in a parent component which will be your final UI.
You can see in the below image we have broken down the UI of GeeksforGeeks’s
homepage into individual components.
4

Components in React basically return a piece of JSX code that tells what should be
rendered on the screen.
Types of Components in React JS :
In React, we mainly have two types of components:
Functional Components:
Functional components are simply javascript functions. We can create a functional
component in React by writing a javascript function. These functions may or may not
receive data as parameters, we will discuss this later in the tutorial. The below example
shows a valid functional component in React:
Syntax for Funtional Components:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}

Class Components:
The class components are a little more complex than the functional components. The
functional components are not aware of the other components in your program whereas the
class components can work with each other. We can pass data from one class component to
another class component. We can use JavaScript ES6 classes to create class-based
components in React. The below example shows a valid class-based component in React:
Syntax for Class Components:
class Democomponent extends React.Component {
render() {
return <h1>Welcome Message!</h1>;
}
}

The components we created in the above two examples are equivalent, and we also
have stated the basic difference between a functional component and a class component.
We will learn about more properties of class-based components in further tutorials.
For now, keep in mind that we will use functional components only when we are sure that
our component does not require interacting or work with any other component. That is,
these components do not require data from other components however we can compose
multiple functional components under a single functional component.
We can also use class-based components for this purpose but it is not recommended as
using class-based components without need will make your application in-efficient.
Rendering Components in ReactJS
React is also capable of rendering user-defined components. To render a component
in React we can initialize an element with a user-defined component and pass this element
as the first parameter to ReactDOM.render() or directly pass the component as the first
argument to the ReactDOM.render() method.
The below syntax shows how to initialize a component to an element:
5

const elementName = <ComponentName />;

In the above syntax, the ComponentName is the name of the user-defined component.
Note: The name of a component should always start with a capital letter. This is done to
differentiate a component tag from HTML tags.
Example: This example renders a component named Welcome to the Screen.
 javascript
// Filename - src/index.js:

import React from "react";


import ReactDOM from "react-dom";

// This is a functional component


const Welcome = () => {
return <h1>Hello World!</h1>;
};

ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
Output: This output will be visible on the http://localhost:3000/ on the browser window.

Explaination:
Let us see step-wise what is happening in the above example:
 We call the ReactDOM.render() as the first parameter.
 React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the
result.
 Then the ReactDOM efficiently updates the DOM to match with the returned element
and renders that element to the DOM element with id as “root”.

Composing Components: Remember in our previous article, our first example of


GeeksforGeeks’s homepage which we used to explain components? Let’s recall what we
have told, “we can merge all of these individual components to make a parent component”.
This is what we call composing components. We will now create individual components
named Navbar, Sidebar, ArticleList and merge them to create a parent component
named App and then render this App component.
The below code in the index.js file explains how to do this:
Filename- App.js:
 javascript
import React from 'react';
6

import ReactDOM from 'react-dom';

// Navbar Component
const Navbar=()=>
{
return <h1>This is Navbar.< /h1>
}

// Sidebar Component
const Sidebar=()=> {
return <h1>This is Sidebar.</h1>
}

// Article list Component


const ArticleList=()=>
{
return <h1>This is Articles List.</h1>
}

// App Component
const App=()=>
{
return(
<div>
<Navbar />
<Sidebar />
<ArticleList />
</div>
);
}

ReactDOM.render(
<App />,
document.getElementById("root")
);
Output:

You can see in the above output that everything worked well, and we managed to merge all
the components into a single component App.
7

Decomposing Components: Decomposing a Component means breaking down the


component into smaller components. We have told the thing about composing smaller
components to build a parent component from the very start when we started discussing
components repeatedly. Let us see why there is a need to do so. Suppose we want to make
a component for an HTML form. Let’s say our form will have two input fields and a
submit button. We can create a form component as shown below:

Filename- App.js:
 javascript
import React from 'react';
import ReactDOM from 'react-dom';

const Form=()=>
{
return (
<div>
<input type = "text" placeholder = "Enter Text.." />
<br />
<br />
<input type = "text" placeholder = "Enter Text.." />
<br />
<br />
<button type = "submit">Submit</button>
</div>
);
}

ReactDOM.render(
<Form />,
document.getElementById("root")
);
Output:

ReactJs-components
Components in React JS is are the core of building React applications. Components are the
building blocks that contains UI elements and logic, making the development process
easier and reusable. In this article we will see how we can create components in React JS.
Prerequisites
8

 HTML and CSS


 JavaScript classes and functions
 JSX
1. React Functional Components:
React functional components can be any JavaScript function that returns the HTML. These
functional components can also accept “props”, meaning properties or data. As these are
JavaScript functions or extensions of JavaScript functions, they can also be created from
the ES6 convention of the arrow function. These functional components can also accept the
props that we can use using JSX syntax and you can also put your normal JavaScript code
before the return statement. One thing to notice is that there should only be one return per
component.
Syntax:
 Javascript
const Greet = (props) => {
const person = props.name;
return (
<div>
<h1>Hello {person}!!</h1>
</div>
)
}
2. React Class-based Components:
The class-based components also have almost the same features as React function
components. but before we define our class-based component, we need to import the
“React. Component” or extract the Component like “{Component}” from React.
import React, {Components} from 'react';
Syntax:
 Javascript
import React, { Component } from 'react'

class App extends Component {


render() {
return (
<div>
<h1>Hello {this.props.name}</h1>
</div>
)
}
}
Rendering the Component:
9

We have successfully made the components, but in order to use them we need to render
them. one can first export their components and can use them anywhere in the
ReactDOM.render method after importing them.
Somewhere in your project in ReactDOM.render()
ReactDOM.render(
<React.StrictMode>
<Greet name="gfg " />
</React.StrictMode>,
document.getElementById('root')
);
Steps to create React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following
command:
cd foldername
Project Structure:

file directory

Example: We will create a card component and pass it to the App function to render it.
 Javascript
// App.js

import React from "react";

function Card({ receiver, writer }) {


return (
<div>
<h1 style={{
backgroundColor: "lightblue",
width: "fit-content"
10

}}>
GeeksforGeeks
</h1>

<h2 style={{
backgroundColor: "lightgrey",
width: "fit-content"
}}>
A Computer Science portal for geeks.
It contains well written, well
thought and well explained computer
science and programming articles
</h2>

<h3>Your truly, {writer}</h3>


</div>
);
}

export default function App() {


return (
<div>
<Card writer="GFG" receiver="gfg jr" />
</div>
);
}
Step to Run Application: Run the application using the following command from the root
directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the
following output:

Output

Class components in React


React class components are the bread and butter of most modern web apps built in
ReactJS. These components are simple classes (made up of multiple functions that add
11

functionality to the application). All class components are child classes for the Component
class of ReactJS.
Creating class Components
We will learn how to create class components with the help of an example
Example: Program to demonstrate the creation of class components. Create a React app
and edit the App.js as:
Filename- App.js:
 javascript
import React from "react";

class App extends React.Component {


render() {
return <h1>GeeksForGeeks</h1>;
}
}

export default App;


Output:

Once a component is declared, it can be used in other components. Program to demonstrate


the use of class components in other components.
Example: Open the App.js file and replace the code with the below code.
 javascript
import React from "react";

class Sample extends React.Component {


render() {
return <h1>A Computer Science Portal For Geeks</h1>;
}
}

class App extends React.Component {


render() {
return <Sample />;
}
}

export default App;


12

Output:

Advantages of class Components over Functional Components


The main feature of class components that distinguished them from functional
components is that they have access to a state which dictates the current behavior and
appearance of the component (Later, with React Hooks introduced in version 16.8, we are
able to declare a stateful component without declaring a class). This state can be modified
by calling the setState() function. One or more variables, arrays, or objects defined as part
of the state can be modified at a time with the setState() function.
Implementing state in class components
let us understand how to use state in class components with the help of an example
Example: Program to demonstrate the use of state in class components. Open
the App.js file and replace the code with the below code.
 javascript
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { change: true };
}
render() {
return (
<div>
<button
onClick={() => {
this.setState({ change: !this.state.change });
}}
>
Click Here!
</button>
{this.state.change ? (
<h1>Welcome to GeeksforGeeks</h1>
):(
<h1>A Computer Science Portal for Geeks</h1>
)}
</div>
);
}
}

export default App;


13

Output:

Passing props in class components


Data is passed to other components with the help of props. Props work similarly for
all components in ReactJS be they class or functional. Props are always passed down from
the parent component to the child component. ReactJS does not allow a component to
modify its own props as a rule. The only way to modify the props is to change the props
being passed from the parent component to the child component. This is generally done by
passing a reference to a function in the parent component, which changes the props being
passed to the child component.
Example: Program to demonstrate the use of props in class components. Open
the App.js file and replace the code with the below code.
 javascript
import React from "react";
class App extends React.Component {
render() {
return <h1>{this.props.data}</h1>;
}
}

class propsExample extends React.Component {


constructor(props) {
super(props);
this.state = { change: true };
}
render() {
return (
<div>
<button
onClick={() => {
this.setState({ change: !this.state.change });
}}
>
Click Here!
</button>
{this.state.change ? (
<App data="Welcome to GeeksforGeeks" />
):(
<App data="A Computer Science Portal for Geeks" />
)}
</div>
14

);
}
}

export default App;

Output:

Lifecycle methods in class components


Class components have access to the lifecycle functions
like componentWillMount(), componentDidMount(),componentWillReceiveProps() ,co
mponentWillUpdate(), shouldComponentUpdate() ,render() and componentWillUnmo
unt();. These lifecycle functions are called at different stages of the lifecycle and are used
for a variety of purposes like changing the state or doing some work (like fetching data
from an external API). They are also referred to as lifecycle hooks.
Example: Program to demonstrate the use of lifecycle hooks. Open the App.js file and
replace the code with the below code.
 javascript
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = { text: "Welcome!" };
}
componentWillMount() {
this.setState({
text: "GeeksforGeeks",
});
}
render() {
return <h1>{this.state.text}</h1>;
}
}

export default App;


Output:
15

Disadvantages of using class components


Class components are slightly slower than their functional counterparts. The
difference is very small and is almost negligible for smaller web apps – though the
performance difference increases when the number of components in the app increases.
Moreover, class components involve a lot more coding on the programmer’s part, making
them slightly more inefficient to use.

Functional Component is one way to create components in a React Application. React.js


Functional Components helps to create UI components in a Functional and more concise
way. In this article, we will learn about functional components in React, different ways to
call the functional component, and also learn how to create the functional components. We
will also demonstrate the use of hooks in functional components
Table of Content
 Functional components in React :
 Ways to call the functional component:
 Problem with using functional components
 Advantage of using hooks in functional components
Functional Components in React :
ReactJS Functional components are some of the more common components that
will come across while working in React. These are simply JavaScript functions. We can
create a functional component in React by writing a JavaScript function. These functions
may or may not receive data as parameters. In the functional Components, the return value
is the JSX code to render to the DOM tree.
Ways to call the functional component:
We can call the functions in javaScript in other ways as follows:
1. Call the function by using the name of the function followed by the Parentheses.
// Example of Calling the function with function name followed by Parentheses
function Parentheses() {
return (<h1>
We can call function using name of the
function followed by Parentheses
</h1>);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(Parentheses());
2. Call the function by using the functional component method.
// Example of Calling the function using component call
function Comp() {
return (<h1> As usual we can call the function using component call</h1>);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Comp />);
16

Now, We will use the functional component method to create a program and see how
functional components render the component in the browser.
Steps to create the React application:
Step 1: Create React Project
npm create-react-app myreactapp
Step 2: Change your directory and enter your main folder charting as
cd myreactapp
Project Structure:

Example 1: This example demonstrates the creation of functional components.


 Javascript
 Javascript
// Filename - index.js
import React from "react";
import ReactDOM from "react-dom";
import Demo from "./App";
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<React.StrictMode>
<Demo />
</React.StrictMode>
);
Step to run the application: Open the terminal and type the following command.
npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/
17

Problem with using functional components


Functional components lack a significant amount of features as compared to class-based
components and they do not have access to dedicated state variables like class-based
components.
Advantage of using hooks in functional components
The problem discussed above is solved with the help of a special ReactJS concept called
“hooks”. ReactJS has access to a special hook called useState(). The useState() is used to
initialize only one state variable to multiple state variables. The first value returned is the
initial value of the state variable, while the second value returned is a reference to the
function that updates it.
Example 2: This example demonstrates the use of useState() hook in functional
component.
 Javascript
 Javascript
// Filename - index.js
import React from "react";
import ReactDOM from "react-dom";
import Example from "./App";
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<React.StrictMode>
<Example />
</React.StrictMode>
);
Step to run the application: Open the terminal and type the following command.
npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/

Functional components do not have access to lifecycle functions like class-based


components do since lifecycle functions need to be defined within the boundaries of a
class. A special React hook called useEffect() needs to be used. It is worth noting
that useEffect() isn’t an exact duplicate of the lifecycle functions – it works and behaves in
a slightly different manner.
Example 3: This example demonstrates the use of useEffect() hook.
 Javascript
 Javascript
// Filename - index.js
18

import React from "react";


import ReactDOM from "react-dom";
import Example from "./App";

const root = ReactDOM.createRoot(


document.getElementById("root")
);
root.render(
<React.StrictMode>
<Example />
</React.StrictMode>
);
Step to run the application: Open the terminal and type the following command.
npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/

Data is passed from the parent component to the child components in the form of
props. ReactJS does not allow a component to modify its own props as a rule. The only
way to modify the props is to change the props being passed to the child component. This
is generally done by passing a reference of a function in the parent component to the child
component.
Example 4: This example demonstrates the use of props.
 Javascript
 Javascript
// Filename - index.js
import React from "react";
import ReactDOM from "react-dom";
import PropsExample from "./App";
const root = ReactDOM.createRoot(
document.getElementById("root")
);
root.render(
<React.StrictMode>
<PropsExample />
</React.StrictMode>
);
Step to run the application: Open the terminal and type the following command.
19

npm start
Output: Open the browser and our project is shown in the URL http://localhost:3000/

React is a JavaScript library for building user interfaces. React makes it painless to
create interactive UIs. Design simple views for each state in your application, and React
will efficiently update and render just the right components when your data changes.
There are about eight different ways to style React JS components, there names and
explanations of some of them are mentioned below.
1. Inline CSS
2. Normal CSS
3. CSS in JS
4. Styled Components
5. CSS module
6. Sass & SCSS
7. Less
8. Stylable
Here are a few examples to style React Components.
Table of Content
 Inline CSS
 Normal CSS
 CSS in JS
 CSS Modules
 Sass and SCSS
Inline CSS:
In inline styling basically, we create objects of style. And render it inside the
components in style attribute using the React technique to incorporate JavaScript variable
inside the JSX (Using ‘{ }’ )
Example 1: This example illustrates how to use inline styling to style react components.
 Javascript
 Javascript
// Filename - App.js

import React, { Component } from "react";


import StudentList from "./StudentList";

const App = () => {


return (
<div>
<StudentList
name="Ashank"
classNo="X"
20

roll="05"
addr="Kolkata, West Bengal"
/>
<StudentList
name="Samir"
classNo="Xi"
roll="09"
addr="Jalpaiguri, West Bengal"
/>
<StudentList
name="Tusar"
classNo="Xii"
roll="02"
addr="Howrah, West Bengal"
/>
<StudentList
name="Karishma"
classNo="ix"
roll="08"
addr="Mednipur, West Bengal"
/>
</div>
);
};

export default App;


Output:

Styling using inline styles

Example 2:
 Javascript
 Javascript
 Javascript
21

// Filename - App.js

import React from 'react';


import Lottery from './Lottery'

function App() {
return (
<div>
<Lottery />
<Lottery title='Mini Daily'/>
</div>
);
}

export default App;


Output:

Inline Styling

Normal CSS:
In the external CSS styling technique, we basically create an external CSS file for each
component and do the required styling of classes. and use those class names inside the
component. It is a convention that name of the external CSS file same as the name of the
component with ‘.css’ extension. It is better if the name of the classes used, follow the
format ‘componentName-context’ (here context signifies where we use this classname).
For example, if we style the header of a component called ‘Box’, a better classname should
style this element should be ‘Box-header’.
Example: This example illustrates how to style react components with external
stylesheets.
 Javascript
 Javascript
 CSS
// Filename - StudentList.js

import React, { Component } from "react";


import StudentList from "./StudentList";
22

import "./App.css

const App = () => {


return (
<div>
<StudentList
name="Ashank"
classNo="X"
roll="05"
addr="Kolkata, West Bengal"
/>
<StudentList
name="Samir"
classNo="Xi"
roll="09"
addr="Jalpaiguri, West Bengal"
/>
<StudentList
name="Tusar"
classNo="Xii"
roll="02"
addr="Howrah, West Bengal"
/>
<StudentList
name="Karishma"
classNo="ix"
roll="08"
addr="Mednipur, West Bengal"
/>
</div>
);
};

export default App;


Output:
23

External CSS styling

CSS in JS:
The’react-jss’ integrates JSS with react app to style components. It helps to write CSS with
Javascript and allows us to describe styles in a more descriptive way. It uses javascript
objects to describe styles in a declarative way using ‘createUseStyles’ method of react-jss
and incorporate those styles in functional components using className attribute.
Step to Install required Module: install third-party react-jss package using the below
command in terminal
npm i react-jss
Example : This example demonstrate the use of react-jss library to add style to react
components.
 Javascript
 Javascript
// Filename - App.js

import React, { Component } from "react";


import StudentList from "./StudentList";

const App = () => {


return (
<div>
<StudentList
name="Ashank"
classNo="X"
roll="05"
addr="Kolkata, West Bengal"
/>
<StudentList
name="Samir"
classNo="Xi"
roll="09"
addr="Jalpaiguri, West Bengal"
/>
<StudentList
name="Tusar"
classNo="Xii"
roll="02"
addr="Howrah, West Bengal"
/>
<StudentList
name="Karishma"
classNo="ix"
roll="08"
24

addr="Mednipur, West Bengal"


/>
</div>
);
};

export default App;


Output:

Styling with CSS in JS

Styled Components: The styled-components allows us to style the CSS under the variable
created in JavaScript. style components is a third party package using which we can create
a component as a JavaScript variable that is already styled with CSS code and used that
styled component in our main component. styled-components allow us to create custom
reusable components which can be less of a hassle to maintain.
Step to Install required Module: install third-party styled-components package using the
below command in terminal.
npm i --save styled-components
Example: This example use styled-cpmponents to create react components.
 Javascript
 Javascript
// Filename - App.js

import React, { Component } from "react";


import StudentList from "./StudentList";

const App = () => {


return (
<div>
<StudentList
name="Ashank"
25

classNo="X"
roll="05"
addr="Kolkata, West Bengal"
/>
<StudentList
name="Samir"
classNo="Xi"
roll="09"
addr="Jalpaiguri, West Bengal"
/>
<StudentList
name="Tusar"
classNo="Xii"
roll="02"
addr="Howrah, West Bengal"
/>
<StudentList
name="Karishma"
classNo="ix"
roll="08"
addr="Mednipur, West Bengal"
/>
</div>
);
};

export default App;


Output :

Styling with styled components

CSS Modules:
26

A CSS module is a simple CSS file but a key difference is by default when it is imported
every class name and animation inside the CSS module is scoped locally to the component
that is importing it also CSS file name should follow the format ‘filename.module.css’.
This allows us to use a valid name for CSS classes without worrying about conflicts with
other class names in your application.
To use CSS modules create a normal CSS file, import the module you have created from
within your component using the syntax
import styles from './filename.module.css
Example :
 Javascript
 Javascript
 CSS
// Filename - App.js

import React, { Component } from "react";


import StudentList from "./StudentList";

const App = () => {


return (
<div>
<StudentList
name="Ashank"
classNo="X"
roll="05"
addr="Kolkata, West Bengal"
/>
<StudentList
name="Samir"
classNo="Xi"
roll="09"
addr="Jalpaiguri, West Bengal"
/>
<StudentList
name="Tusar"
classNo="Xii"
roll="02"
addr="Howrah, West Bengal"
/>
<StudentList
name="Karishma"
classNo="ix"
roll="08"
addr="Mednipur, West Bengal"
/>
27

</div>
);
};

export default App;


Output :

Styling with CSS modules

Sass and SCSS:


Sass is the most stable, powerful, professional-grade CSS extension language. It’s a CSS
preprocessor that adds special features such as variables, nested rules, and mixins or
syntactic sugar in regular CSS. The aim is to make the coding process simpler and more
efficient.
Installation Steps:
 Step 1: Before moving further, firstly we have to install node-sass , by running the
following command in your project directory, with the help of terminal in your SRC
folder or you can also run this command in Visual Studio Code’s terminal in your
project folder.

npm install node-sass


 Step 2 : After the installation is complete we create a file name StudentList.scss .
 Step 3: Now include the necessary CSS effects in your CSS file.
 Step 4: Now we import our file the same way we import a CSS file in React.
 Step 5: In your app.js file, add this code snippet to import StudentList.scss.
import './ StudentList.scss';
Example: This example demonstrate above approach.
 Javascript
 Javascript
 CSS
// Filename - App.js

import React, { Component } from "react";


28

import StudentList from "./StudentList";

const App = () => {


return (
<div>
<StudentList
name="Ashank"
classNo="X"
roll="05"
addr="Kolkata, West Bengal"
/>
<StudentList
name="Samir"
classNo="Xi"
roll="09"
addr="Jalpaiguri, West Bengal"
/>
<StudentList
name="Tusar"
classNo="Xii"
roll="02"
addr="Howrah, West Bengal"
/>
<StudentList
name="Karishma"
classNo="ix"
roll="08"
addr="Mednipur, West Bengal"
/>
</div>
);
};

export default App;


Output :
29

Styling using Sass

ReactJS Props – Set 1


Till now we were working with components using static data only. In this article, we will
learn about how we can pass information to a Component.
What is props?
React allows us to pass information to a Component using something called props (which
stands for properties). Props are objects which can be used inside a component.
Passing and Accessing props
We can pass props to any component as we declare attributes for any HTML tag.
Syntax:
// Passing Props
<DemoComponent sampleProp = "HelloProp" />
In the above code snippet, we are passing a prop named sampleProp to the component
named DemoComponent. This prop has the value “HelloProp”. Let us now see how can we
access these props.
We can access any props inside from the component’s class to which the props is passed.
Syntax:
// Accessing props
this.props.propName;
The ‘this.props’ is a kind of global object which stores all of a component’s props.
The propName, that is the names of props are keys of this object.
Let us see an example where we will implement passing and accessing props.
In the below example, we will use a class-based component to illustrate the props. But we
can also pass props to function-based components and going to pass in the below example.
To access a prop from a function we do not need to use the ‘this’ keyword anymore.
Functional components accept props as parameters and can be accessed directly.
Open your react project and edit the index.js file in the src folder:
Example: Write the following code in your index.js file.
 javascript
import React from 'react';
import ReactDOM from 'react-dom/client';

// sample component to illustrate props


class DemoComponent extends React.Component{
render(){
return(
<div>
{/*accessing information from props */}
<h2>Hello {this.props.user}</h2>
<h3>Welcome to GeeksforGeeks</h3>
</div>
);
30

}
}

const root = ReactDOM.createRoot(document.getElementById("root"));


root.render(
<React.StrictMode>
<DemoComponent />
</React.StrictMode>
);
Output: This will be the output of the above program

Open your react project and edit the index.js file in the src folder:
Example: Write the following code in your index.js file.
 Javascript
import React from 'react';
import ReactDOM from 'react-dom/client';

// functional component to illustrate props


function DemoComponent(props){
return(
<div>
{/*accessing information from props */}
<h2>Hello {props.user}</h2>
<h3>Welcome to GeeksforGeeks</h3>
</div>
);
}

const root = ReactDOM.createRoot(document.getElementById("root"));


root.render(
<React.StrictMode>
<DemoComponent user="Geeks"/>
</React.StrictMode>
);

Output:
Passing information from one component to another
This is one of the coolest features of React. We can make components to interact among
themselves. We will consider two components Parent and Children to explain this. We will
31

pass some information as props from our Parent component to the Child component. We can
pass as many props as we want to a component.
Look at the below code:
Open your react project and edit the index.js file in the src folder:
Example: Write the following code in your index.js file.
 javascript
import React from 'react';
import ReactDOM from 'react-dom/client';

// Parent Component
class Parent extends React.Component{
render(){
return(
<div>
<h2>You are inside Parent Component</h2>
<Child name="User" userId = "5555"/>
</div>
);
}
}

// Child Component
class Child extends React.Component{
render(){
return(
<div>
<h2>Hello, {this.props.name}</h2>
<h3>You are inside Child Component</h3>
<h3>Your user id is: {this.props.userId}</h3>
</div>
);
}
}

const root = ReactDOM.createRoot(document.getElementById("root"));


root.render(
<React.StrictMode>
<Parent/>
</React.StrictMode>
);
Output: See the output of this program
32

What is this.props in React?


So we have seen props in React and also have learned about how props are used, how they
can be passed to a component, how they are accessed inside a component, and much more.
We have used the thing “this.props.propName” very often in this complete scenario to access
props. Let us now check what is actually being stored in this. We will console.log
“this.props” in the above program inside the child component and will try to observe what is
logged into the console. Below is the modified program with console.log() statement:
Open your react project and edit the index.js file in the src folder:
Example: Write the following code in your index.js file.
 javascript
import React from 'react';
import ReactDOM from 'react-dom/client';

// Parent Component
class Parent extends React.Component{
render(){
return(
<div>
<h2>You are inside Parent Component</h2>
<Child name="User" userId = "5555"/>
</div>
);
}
}

// Child Component
class Child extends React.Component{
render(){
console.log(this.props);
return(
<div>
<h2>Hello, {this.props.name}</h2>
<h3>You are inside Child Component</h3>
<h3>Your user id is: {this.props.userId}</h3>
</div>
);
}
}
33

const root = ReactDOM.createRoot(document.getElementById("root"));


root.render(
<React.StrictMode>
<Parent/>
</React.StrictMode>
);

Output:
You can clearly see in the above image that in the console it is shown that the this.props is
an object and it contains all of the props passed to the child component. The props name of
the child component are keys of this object and their values are values of these keys. So, it is
clear now that whatever information is carried to a component using props is stored inside an
object.

React Props Validation


Props are an important mechanism for passing the read-only attributes to React components.
The props are usually required to use correctly in the component. If it is not used correctly,
the components may not behave as expected. Hence, it is required to use props validation in
improving react components.
Props validation is a tool that will help the developers to avoid future bugs and problems. It
is a useful way to force the correct usage of your components. It makes your code more
readable. React components used special property PropTypes that help you to catch bugs by
validating data types of values passed through props, although it is not necessary to define
components with propTypes. However, if you use propTypes with your components, it helps
you to avoid unexpected bugs.
Validating Props
App.propTypes is used for props validation in react component. When some of the props
are passed with an invalid type, you will get the warnings on JavaScript console. After
specifying the validation patterns, you will set the App.defaultProps.
Syntax:
1. class App extends React.Component {
2. render() {}
3. }
4. Component.propTypes = { /*Definition */};
ReactJS Props Validator
ReactJS props validator contains the following list of validators.
S PropsType Description
34

1. PropTypes.any The props can be


of any data type.

2. PropTypes.array The props should


be an array.

3. PropTypes.bool The props should


be a boolean.

4. PropTypes.func The props should


be a function.

5. PropTypes.number The props should


be a number.

6. PropTypes.object The props should


be an object.

7. PropTypes.string The props should


be a string.

8. PropTypes.symbol The props should


be a symbol.

9. PropTypes.instanceOf The props should


be an instance of
a particular
JavaScript class.

10. PropTypes.isRequired The props must


be provided.

11. PropTypes.element The props must


be an element.

12. PropTypes.node The props can


render anything:
numbers, strings,
elements or an
array (or
fragment)
35

containing these
types.

13. PropTypes.oneOf() The props should


be one of several
types of specific
values.

14. PropTypes.oneOfType([PropTypes.string,PropTypes.number]) The props should


be an object that
could be one of
many types.
Example
Here, we are creating an App component which contains all the props that we need. In this
example, App.propTypes is used for props validation. For props validation, you must have
to add this line: import PropTypes from 'prop-types' in App.js file.
App.js
1. import React, { Component } from 'react';
2. import PropTypes from 'prop-types';
3. class App extends React.Component {
4. render() {
5. return (
6. <div>
7. <h1>ReactJS Props validation example</h1>
8. <table>
9. <tr>
10. <th>Type</th>
11. <th>Value</th>
12. <th>Valid</th>
13. </tr>
14. <tr>
15. <td>Array</td>
16. <td>{this.props.propArray}</td>
17. <td>{this.props.propArray ? "true" : "False"}</td>
18. </tr>
19. <tr>
20. <td>Boolean</td>
21. <td>{this.props.propBool ? "true" : "False"}</td>
22. <td>{this.props.propBool ? "true" : "False"}</td>
23. </tr>
24. <tr>
25. <td>Function</td>
36

26. <td>{this.props.propFunc(5)}</td>
27. <td>{this.props.propFunc(5) ? "true" : "False"}</td>
28. </tr>
29. <tr>
30. <td>String</td>
31. <td>{this.props.propString}</td>
32. <td>{this.props.propString ? "true" : "False"}</td>
33. </tr>
34. <tr>
35. <td>Number</td>
36. <td>{this.props.propNumber}</td>
37. <td>{this.props.propNumber ? "true" : "False"}</td>
38. </tr>
39. </table>
40. </div>
41. );
42. }
43.}
44.App.propTypes = {
45. propArray: PropTypes.array.isRequired,
46. propBool: PropTypes.bool.isRequired,
47. propFunc: PropTypes.func,
48. propNumber: PropTypes.number,
49. propString: PropTypes.string,
50.}
51.App.defaultProps = {
52. propArray: [1,2,3,4,5],
53. propBool: true,
54. propFunc: function(x){return x+5},
55. propNumber: 1,
56. propString: "JavaTpoint",
57.}
58.export default App;
Main.js
1. import React from 'react';
2. import ReactDOM from 'react-dom';
3. import App from './App.js';
4.
5. ReactDOM.render(<App/>, document.getElementById('app'));
Output:
37

ReactJS Custom Validators


ReactJS allows creating a custom validation function to perform custom validation. The
following argument is used to create a custom validation function.
ADVERTISEMENT
ADVERTISEMENT
o props: It should be the first argument in the component.
o propName: It is the propName that is going to validate.
o componentName: It is the componentName that are going to validated again.
Example
1. var Component = React.createClass({
2. App.propTypes = {
3. customProp: function(props, propName, componentName) {
4. if (!item.isValid(props[propName])) {
5. return new Error('Validation failed!');
6. }
7. }
8. }
9. })

You might also like