Master React: The Ultimate Beginner's Guide to JSX, Components and Props
😉📝Let's Play with JSX in React
Jsx can be divided into two parts. Javascript(js) and Extensible Markup Language (XML).
In simple words, JSX is an HTML-like syntax used by React that extends ECMAScript so that HTML-like syntax can co-exist with JavaScript/React code.
JSX allows you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file where you write JavaScript code, then the preprocessor will transform these expressions into actual JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children.
🤔Why use Jsx
It is faster than regular JavaScript because it performs optimization while translating the code into JavaScript.
It is type-safe, and most errors can be found at compilation time.
It makes it easier to create templates.
So, isn’t jsx good to use? Of course, yes….🙌
⁉️React Components
Component…...
Is a core building block in a React.
Allows you to break down your UI into reusable pieces that can manage their own state/display content.
So it means, anything can be reusable will be component*, most importantly it should return jsx.*
For instance, headers can be utilized on multiple pages, even with footers that make them components. however, if I have let’s say 2 files that are not reusable are not considered components.
Types of Components:
Functional Component
Class Component
- Functional Components: Start with the
function
keyword and use JSX to define the UI.
function Greeting() {
return <h1>Hello, World!</h1>;
}
- Class Components: Use ES6
class
syntax and extendReact.Component
.
class Greeting extends React.Component {
render() {
return <h1>Hello, World!</h1>;
}
}
😌We will use Functional Components
Because it is easier to write
hooks like useState and useEffect Allow Funcitnoal components to handle state and its lifecycle
The functional component’s lifecycle is managed by hooks (useEffect) and the class component is managed by usecomponentDidMount,componentDidUpdate, and componentWillUnmount
🤔We kept talking about React Component lifecycle but what is React component lifecycle??
React Component Lifecycle → A component goes through 3 different stages :
Mounting (Birth): When the react component is created and added to the screen
Class Component:
componentDidMount()
runs.Functional Component: The
useEffect()
with no dependencies ([]
) runs.
// Functional Component
useEffect(() => {
console.log("Component mounted!");
}, []);
Updating (Growth): When a component is updated/changes due to new data [eg. props/state changes]
Class Component:
componentDidUpdate()
runs after updates.Functional Component: The
useEffect()
runs whenever its dependencies (e.g.,state
,props
) change.
useEffect(() => {
console.log("Component updated!");
}, [someDependency]);
Unmounting (Death): When the component is removed from the screen and cleared up
Class Component:
componentWillUnmount()
runs.Functional Component: A cleanup function inside
useEffect()
runs
useEffect(() => {
console.log("Component is alive!");
return () => {
console.log("Component unmounted!");
};
}, []);
⁉️Why Lifecycle is important?
Mounting: Setting up things like fetching data from API or initializing resources.
Updating: changing the component
Unmounting: Cleaning up resources like event listeners or timers to avoid memory leaks.
✍️Let’s dive into props in React
Props are nothing but a special type of keyword in react that stands for Properties and is used for passing data from one component to another,
When you pass data with props, they are passed in an unidirectional flow from parent to child.
* Suppose there are 2 files named App.jsx and Card.jsx [under component folder]
Every file whether it can be app.jsx or any other file has access to pass and get props, so we set props in the app. jsx to see how we can get props in Card.jsx
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import Card from './components/Card'
function App() {
// const [count, setCount] = useState(0)
let myObj = {
username: "mash",
pass: "123"
}
let myArr = [1, 2, 3, 4, 5];
return (
<>
<Card userName="MashTechie" editor="vsCode" exampleObj={myObj} exampleArr={myArr} />
</>
)
}
export default App
Card.jsx
function Card(props) {
//some code
console.log("props -> ", props);
}
Output:
Extended:
This is the output when you use props and fetch data.
Now, let’s display the name and button text using props, to make it happen, we need to configure CSS. We will use tailwind CSS you can refer to tailwind CSS documentation framework section's vite bundle to get it configured
.
After configuring, our Card. jsx be like :
Card.jsx
import React from 'react'
// If anyone forgets to pass props in btnTxt then the btnTxt should have set his default name in this way -> btnTxt ="visit me "
function Card({ userName, btnTxt = "visit me" }) {
// console.log("Props -> ", props.userName);
return (
<>
<div>Card</div>
{/* <div>Card</div> */}
<figure className="bg-slate-100 rounded-xl p-8 dark:bg-slate-800">
<img className="w-24 h-24 rounded-full mx-auto" src="/sarah-dayan.jpg" alt="" width="384" height="512" />
<div className="pt-6 space-y-4">
<blockquote>
<p className="text-lg font-medium">
“Tailwind CSS is the only framework that I've seen scale
on large teams. It’s easy to customize, adapts to any design,
and the build size is tiny.”
</p>
</blockquote>
<figcaption className="font-medium">
<div className="text-sky-500 dark:text-sky-400">
{/* {props.userName} */}
{userName}
</div>
</figcaption>
<button type="button">
{/* {props.btnTxt} */}
{btnTxt}
</button>
</div>
</figure>
</>
)
}
export default Card
App.jsx
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import Card from './components/Card'
function App() {
// const [count, setCount] = useState(0)
let myObj = {
username: "mash",
pass: "123"
}
let myArr = [1, 2, 3, 4, 5];
return (
<>
<h1 className='bg-green-500 text-black p-5 rounded-2xl'>Tailwind Css</h1>
<Card userName="mashtechie" btnTxt="visit me profile" />
<Card userName="mmip" />
</>
)
}
export default App
Here, we pass the userName, and button Text to the Card.jsx since we have to render the userName and btnTxt, and if the btnTxt is not coming from App.jsx, we can set a default name.