Introduction to React and Its Benefits
Picture this: it's 2013 and Facebook engineers are drowning in complex code while trying to make the newsfeed faster and more interactive. Enter React, their savior, designed to make building dynamic user interfaces a breeze.
React is all about components. Think of them as Lego bricks; you build a web app by snapping together these reusable pieces, creating a structure that's both strong and flexible. Why care about React? If you've ever waited for a web page to load, you'll love React's speed. Its virtual DOM updates only the parts that change, avoiding full page reloads for lightning-fast updates.
Plus, if you wanted to transition into mobile app development, React Native lets you create native iOS and Android apps using the same principles. Companies like Airbnb and Tesla use it for sleek mobile experiences.
Setting Up Your First React App
Ready to start your React journey? First, you'll need Node.js and npm. Think of npm as your app's personal shopper, fetching all the packages you need. With these tools in hand, creating a new React app is a piece of cake.
After that, just open your terminal and type npx. Next, type create-react-app followed by your app's name. This tool provides a boilerplate setup with a standard directory structure and configuration. If you've already created a folder with the name you want, just type ./ to put the boilerplate into the same folder. Voila, you've built your React app from scratch.
The Public Folder and Static Assets
Once your app is set up, you'll notice a well-organized folder structure. Understanding this layout is key to mastering React. On the root directory, it contains configuration files and folders that are essential for your project.
First, we have the node_modules directory. This directory contains all the dependencies and sub-dependencies your project relies on to function correctly. For example, for React to function correctly, it needs a lot of commands and programming behind the scenes. The node_modules directory handles all of that.
After node_modules is the public folder. This folder contains static assets that will be served directly by the web server. For example, inside this public folder is the index.html. This file contains a div with an ID of root where your React app will be injected. It serves as the entry point for your app; when someone visits your website, the browser loads this file first. We will discuss more about it later.
Next, we have the manifest.json file. This JSON file provides important metadata about your web application, such as the app name, icons, theme colors, and display settings. Additionally, you'll find the favicon.ico file here. This is a small icon associated with your website, displayed by web browsers and other software to help users visually identify your site.
You will also see various logos here because the public folder serves static assets. Serving static assets makes your website faster, more reliable, and easier to manage. You can create a folder named images within the public folder to store your images. Similarly, you can create folders named fonts, videos, and any other static assets you need. And finally, you also have the robots.txt file here. This is a valuable tool for controlling how web crawlers interact with your site. It helps you manage crawler traffic, prevent the indexing of sensitive content, and optimize your site's SEO.
The Source Folder: index.js and app.js
After the public folder, let's move on to the source folder. The source folder is like the heart of your React project. It holds all the main code and files you need to create and run your app.
The most important file here is index.js. This file is where your app starts. It's like the first step in getting your app to show up on the screen. Inside index.js is where you render your first component, which is typically App.js. This rendering process is handled by ReactDOM.render. This process effectively connects the React application to the static HTML structure provided in index.html.
And finally, we wrap your App component with React.StrictMode so that it will highlight potential problems in the application during development, which is good for debugging.
After index.js, you'll find App.js. This file is like the starting point for your whole application. Here you can build and organize your app's user interface and functionality. It's where you create and arrange all the different parts of your app, like buttons, forms, and pages. It's like when you're building with vanilla HTML and CSS, this is your index.html. Inside here is the boilerplate code set up by React. You can now run your React app using the command npm start.
Understanding JSX
Inside App.js, the code isn't just HTML or JavaScript; it's a unique blend of both. This magical blend is known as JSX, short for JavaScript XML.
JSX is where JavaScript's dynamic power meets the simplicity of HTML. For instance, JSX allows you to embed JavaScript expressions within curly braces directly in your HTML-like code. This means you can dynamically insert values or execute JavaScript logic right within your JSX components. Or you can write multiple lines of HTML inside parentheses like this one.
Creating Reusable Function Components
But who wants to keep rewriting the same JSX code for every single page? Imagine having to maintain thousands of blog posts. That's enough to drive anyone crazy. So React introduces what we call function components. If you peek into the App.js, you'll find an example of a function component.
A function component has four parts. Firstly, is the function definition. A function component starts with defining a JavaScript function. This function can have any name, but by convention, it starts with an uppercase letter. In our case, it is named App. After that comes the return statement. This statement tells React what to display when the component is used. Here, you define the JSX structure and content that will make up your UI when the component is displayed. It's where you assemble the elements to create the visual and interactive experience for your users. And finally, you can export your function component. Why do we do this? We do this so that other components can also use it.
For example, to create a button component, you would create a folder named components inside the source directory and then create a file named button.jsx. Inside this file, you define your function component and its JSX structure within the return statement and then export it. By doing this, we can now access the button.jsx in App.js by importing it and including it within our return statement.
Styling Components with CSS
But how do we style this button component? As you can see, we have a file called App.css. Inside this file is all the boilerplate design we already saw earlier when we ran our React app. For now, let's remove everything and start from scratch. This file is like your ordinary vanilla CSS. Here you can design your HTML as usual, but the difference you'll see is in how we declare the class selector. In React, we don't declare it as class in JSX but as className. For example, let's go to our button.jsx and give this button a className of btn. And if we go to App.css, we can now design this button.
But what if we have a lot of components and pages to design? We can't just keep writing in the same CSS file, right? Well, you can create another CSS file inside the source folder and then import it in the component file, which in our case is button.jsx. This is the same case with index.css, which is primarily imported in index.js to style the body and font family.
After learning how to design your pages and components, let's now move on to app.test.js and the other files. Testing is a critical part of software development, which is why React provides tools and frameworks for testing components. app.test.js is a file where we write tests for our App component, usually using the Jest testing framework along with React Testing Library. But this is another topic that we will discuss in the future. For now, let's focus on the basics of React.
Finally, is the reportWebVitals file. This is a function that measures and reports the performance metrics of your web application, such as page load times and user interaction timings.
Project Configuration Files
After learning about the source folder, we can now move on to the other files like .gitignore. The .gitignore file is used to prevent certain files from being accidentally committed to Git, for example, leaking an API key like OpenAI API keys has become a recent topic. And finally is the package.json and package-lock.json. package.json file holds important information about your project and lists the tools and libraries it needs. And package-lock.json is automatically created to make sure everyone who installs your project gets the exact same versions of those tools and libraries, so things work the same way every time.
Component Reusability and Introducing Props
Now that we understand the folder structure of React, let's move on to components. Earlier, we built our first component, which was a button. Components in React are reusable building blocks that encapsulate HTML and JavaScript logic into self-contained units. For example, we have here is a three-card div inside a card container. What we usually do in vanilla HTML and CSS is that we wrap them in a div container and then hardcoded the same card with different card name and description, right? But what if we can just make a single card and then use them everywhere without writing the same code? That's how components work.
For example, we can just create a new JSX file called card inside the component folder and then write a function component called card with all the HTML for your card, and then export it. And then in App.js, create a div with the class card-container and place three card components inside. Now you have three cards without repeating the same code. Want each card to have its own button? Just add a button inside of the card component. Now every card gets its own button automatically. But wait, we don't want all the cards to look the same. This is where props come to the rescue. Props let you send data from one component to another.
Advanced Prop Techniques
So to customize each card's name and description, use props to make these values dynamic and changeable. Props make it super easy and fun to create unique, reusable components in React. To use props in your card component, just add props inside of the parentheses of your function. Then you can get the card's name with props.name and the description with props.description. Next, in App.js, you can customize your card's name and description. Use curly braces to write card name and card description as props.
But what if your card description is super long? No problem. Use constants to keep your code neat and readable. What if you have tons of data to pass and writing out each prop name feels like a chore? Use an object to pass multiple props at once. For example, if your cards are now employee cards with details like name, age, position, and salary, you can bundle all these into an object. Objects are like boxes that hold multiple pieces of information. The key is the name and the value can be anything: a string, number, array, or even another object. Here's where the spread operator comes in handy. It helps you access all the props in one go. You can use the spread operator to unpack everything inside the object quickly and easily.
Managing State with the useState Hook
After learning about creating components and using props, let's dive into managing state in React. State in React is like a component's memory that keeps track of information. For example, in our earlier card components, the content was fixed. But what if we want a card that updates, like a counter? We need the card to remember the current count and update it when needed. Enter useState. useState gives us two things: the current state and a function to update it. This lets components change what users see based on events or new data.
Let's create a simple card counter. Make a new file in the components folder named CardCounter and import it into App.js. In CardCounter, we'll show the card name, the count value, and two buttons. These buttons will have onClick events for increment and decrement. First, import useState and initialize it with a starting value of zero. The first value from useState is the current count, starting at zero. The second value is a function, setCount, to update the count. Instead of hard-coding zero, use curly braces to show the current count dynamically. In the increment and decrement functions, use setCount to update the count. For example, setCount increases the count when the increment button is clicked.
Conditional Rendering and Ternary Operators
And that's just one simple way to use useState. You can also use it for conditional rendering. For example, imagine you start with useState with a value of false. When you click a button, it toggles the state, acting like an on-and-off switch. Inside the button, you can use a ternary operator to decide what gets shown. If you're not familiar, a ternary operator is a neat way to write conditional statements. It works with three parts: a condition to be validated, and after that it will execute expression one if true and expression two if false. Ternary operators are super handy in React because they let you write clear and efficient conditional logic right inside your JSX and JavaScript code.
And I know we've discussed a lot of concepts today, which is why we've made a PDF version of this video. It's free, but we would really appreciate any support you give to the channel. For more learning material, check out the PDF file for roadmaps, beginner projects, and more. This is just the basics of React. We will still discuss how routing works and how forms work here in React, so subscribe to stay tuned for that. Well, that's it for now. Thank you for watching.