Introduction to
React.js
React.js is a JavaScript library developed
by Facebook to create user interfaces.
We use React to build single-page
applications.
In React, we can create reusable
components, making our work easier to
develop the UI.
npm create vite@latest my-react-app
npm install
npm run dev
import React from 'react';
function App() {
return <h1>Hello, React!</h1>;
}
export default App;
What is a Single Page
Application?
A single-page application is an application
where clicking on any tab, nav menu, or
other links does not reload the entire
application, only the content of the body
is reloaded for the new section.
Like we have two tabs on youtube movies and
songs when I switch to songs from the movie so
it will not reload the whole application it just
reload the body content of songs section
What is a Component
in React?
A component in React is an independent,
reusable piece of code that we can use
multiple times. For example, if I create a
component for a red button, I can use it
anywhere in the application. This way, we
can create many components that help
make application development easier.
There are two types of components: class
and functional :
// src/RedButton.jsx
import React from 'react';
function RedButton() {
return <button style={{ backgroundColor: 'red'
}}>Click Me</button>;
}
export default RedButton;
// src/App.jsx
import React from 'react';
import RedButton from './RedButton';
function App() {
return (
<div>
<RedButton />
<RedButton />
</div>
);
}
export default App;
What is JSX?
JSX is a combination of HTML and
JavaScript, which means we can write
HTML-like code inside a JavaScript file.
// src/App.jsx
import React from 'react';
function App() {
const name = 'Shaaz';
return <h1>Hello, {name}!</h1>;
}
export default App;
Rules of JSX :
Wrap JSX in a single element:.
// src/App.jsx
function App() {
return (
<div>
<h1>Hello, World!</h1>
</div>
);
}
Use a ternary operator instead of if-
else:
// src/App.jsx
function App({ isLoggedIn }) {
return
<div>{isLoggedIn ?
<h1>Welcome Back!</h1> : <h1>Please Sign
In</h1>}
</div>;
}
Use {} to embed JavaScript expressions:
// src/App.jsx
function App() {
const name = 'Shaaz';
return <h1>Hello, {name}!</h1>;
}