Welcome to the ultimate guide to get you started with React.js. Let's dive into the React universe, where you’ll learn the essential concepts you’ll use daily. It’s like learning to cook: master the basics, and you can whip up anything from a simple sandwich to a fancy gourmet dish.
What You’ll Learn:
- How to create and nest components
- How to add markup and styles
- How to display data
- How to render conditions and lists
- How to respond to events and update the screen
- How to share data between components
Creating and Nesting Components: Assemble Your Superhero Squad
React apps are made out of components. Think of a component as a piece of the UI (user interface) with its own logic and appearance. It can be as small as a button or as large as an entire page.
Step 1: Creating a Simple Component
Imagine you’re introducing a new superhero to your squad. Here’s our first superhero: a button!
function MyButton() {
return <button>I'm a button</button>;
}
Our hero is simple but effective. It’s a JavaScript function that returns a bit of HTML (called JSX in React). Now, let’s nest this superhero into another component, like adding Batman to the Justice League.
Step 2: Nesting Components
Just like Batman works better with his team, our button can be part of a bigger component. Let’s create an app that welcomes users with a button.
export default function MyApp() {
return (
<div>
<h1>Welcome to my app</h1>
<MyButton />
</div>
);
}
Notice that <MyButton />
starts with a capital letter. That’s the rule: React component names always start with a capital letter, while HTML tags are lowercase. Think of it as giving your heroes proper names.
Writing Markup with JSX: Speak the Superhero Language
The markup syntax you’ve seen above is called JSX. It’s optional but super convenient. JSX is stricter than HTML. You have to close tags like <br />
and wrap multiple tags in a shared parent, like <div>...</div>
or an empty <>...</>
wrapper.
function AboutPage() {
return (
<>
<h1>About</h1>
<p>
Hello there.
<br />
How do you do?
</p>
</>
);
}
Think of JSX as the secret superhero language. You can use an online converter to turn regular HTML into JSX if you need help translating.
Adding Styles: Dressing Up Your Superheroes
In React, you specify a CSS class with className
. It works the same way as the HTML class
attribute. Let’s give our hero a stylish costume.
<img className='avatar' />
Write the CSS rules in a separate file:
/* In your CSS */
.avatar {
border-radius: 50%;
}
React doesn’t dictate how you add CSS files. Use a <link>
tag in your HTML or follow the documentation for your build tool or framework.
Displaying Data: Show Off Your Superhero Stats
JSX lets you mix JavaScript with HTML. Curly braces {}
let you escape back into JavaScript to display data. For example, let’s display a user’s name:
const user = { name: 'Hedy Lamarr' };
return <h1>{user.name}</h1>;
You can also use curly braces for attributes:
const user = { imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg' };
return <img className='avatar' src={user.imageUrl} />;
For complex expressions, like string concatenation:
const user = {
name: 'Hedy Lamarr',
imageUrl: 'https://i.imgur.com/yXOvdOSs.jpg',
imageSize: 90,
};
export default function Profile() {
return (
<>
<h1>{user.name}</h1>
<img
className='avatar'
src={user.imageUrl}
alt={'Photo of ' + user.name}
style={{
width: user.imageSize,
height: user.imageSize,
}}
/>
</>
);
}
Conditional Rendering: Superhero Decisions
React uses regular JavaScript for conditions. For example, you can use an if
statement to include JSX conditionally:
let content;
if (isLoggedIn) {
content = <AdminPanel />;
} else {
content = <LoginForm />;
}
return <div>{content}</div>;
For a more compact approach, use the conditional ?
operator:
<div>{isLoggedIn ? <AdminPanel /> : <LoginForm />}</div>
Or use the logical &&
operator when you don’t need an else branch:
<div>{isLoggedIn && <AdminPanel />}</div>
Rendering Lists: The Superhero Roster
Use JavaScript’s map()
function to render lists of components. Imagine you have an array of products:
const products = [
{ title: 'Cabbage', id: 1 },
{ title: 'Garlic', id: 2 },
{ title: 'Apple', id: 3 },
];
const listItems = products.map((product) => (
<li key={product.id}>{product.title}</li>
));
return <ul>{listItems}</ul>;
Each <li>
needs a key
attribute, usually from your data, like a database ID.
Responding to Events: Superhero Actions
Respond to events by declaring event handler functions inside your components:
function MyButton() {
function handleClick() {
alert('You clicked me!');
}
return <button onClick={handleClick}>Click me</button>;
}
Notice how onClick={handleClick}
has no parentheses at the end. You only pass the function; React will call it when the event occurs.
Updating the Screen: Superhero State
To remember some information, like how many times a button is clicked, add state to your component. First, import useState
from React:
import { useState } from 'react';
Declare a state variable inside your component:
function MyButton() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}
useState
gives you the current state (count
) and a function to update it (setCount
). Clicking the button updates the state and re-renders the component.
If you render the same component multiple times, each gets its own state:
import { useState } from 'react';
export default function MyApp() {
return (
<div>
<h1>Counters that update separately</h1>
<MyButton />
<MyButton />
</div>
);
}
Sharing Data Between Components: Superhero Team Coordination
Sometimes, components need to share data and update together. Move the state “upwards” to the closest common component. Here’s how:
First, move the state up from MyButton
into MyApp
:
export default function MyApp() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<div>
<h1>Counters that update together</h1>
<MyButton count={count} onClick={handleClick} />
<MyButton count={count} onClick={handleClick} />
</div>
);
}
Pass the state and click handler down as props:
function MyButton({ count, onClick }) {
return <button onClick={onClick}>Clicked {count} times</button>;
}
When you click a button, handleClick
updates the state in MyApp
, which then passes the updated state to both MyButton
components. This is called “lifting state up”.
Conclusion
Congratulations! You’ve taken your first steps into the world of React and learned how to create, nest, style, and manage state in components. With these superpowers, you’re ready to build amazing, interactive web apps. Keep experimenting, stay curious, and remember: with great power comes great responsibility (and lots of fun coding adventures)!
Happy Coding!
contact with me:
Top comments (0)