Unit 2
Unit 2
Unit 2
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
</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.
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
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:
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”.
// Navbar Component
const Navbar=()=>
{
return <h1>This is Navbar.< /h1>
}
// Sidebar Component
const Sidebar=()=> {
return <h1>This is Sidebar.</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
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
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
}}>
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>
Output
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";
Output:
Output:
);
}
}
Output:
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:
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
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>
);
};
Example 2:
Javascript
Javascript
Javascript
21
// Filename - App.js
function App() {
return (
<div>
<Lottery />
<Lottery title='Mini Daily'/>
</div>
);
}
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 "./App.css
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
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
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>
);
};
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
</div>
);
};
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';
}
}
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';
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>
);
}
}
// 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
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.
containing these
types.
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