logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Building a Simple React Application: Putting It All Together

author
Generated by
Abhishek Goyan

24/08/2024

React

Sign in to read full article

React is one of the most popular JavaScript libraries for building user interfaces, and it's often used to create single-page applications (SPAs). If you're new to React or looking to improve your skills, you'll want to familiarize yourself with its core concepts and how they fit together in a complete application. Let's dive in!

Prerequisites

Before we get started, make sure you have the following set up on your machine:

  1. Node.js: Download and install Node.js from the official website. This will also install npm (Node Package Manager), which we need to manage our packages.

  2. A Code Editor: Use a code editor of your choice (like Visual Studio Code, Sublime Text, or Atom).

  3. Basic Knowledge of JavaScript: Familiarity with JavaScript, HTML, and CSS will be beneficial as we progress through the tutorial.

Setting Up the Development Environment

Create a New React Application

The easiest way to create a new React app is by using Create React App, a command-line tool developed by Facebook. Open your terminal and run the following command:

npx create-react-app my-simple-app

This command creates a new directory called my-simple-app with a default project structure, including all the necessary build setup.

Navigate to Your App Directory

After the installation is complete, navigate to your newly created app folder:

cd my-simple-app

Start the Development Server

Now that you're inside your project directory, you can start the development server with the command:

npm start

This will launch your app in the browser at http://localhost:3000, where you should see the default welcome page for Create React App.

Understanding the Project Structure

When you look at the folder structure created by Create React App, you'll find the following key folders and files:

  • public/: Contains the index.html file—the entry point for your React app.
  • src/: This is where you’ll spend most of your time. It holds the JavaScript files, components, and styles.
  • package.json: Lists the dependencies for your app and scripts to run tasks.

Building Components

In React, a component is a reusable piece of UI that can manage its own state. Let's build a simple counter component.

Creating the Counter Component

  1. Inside the src/ directory, create a new folder named components.
  2. Inside components, create a file named Counter.js and add the following code:
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div style={{ textAlign: 'center', marginTop: '20px' }}> <h1>Counter: {count}</h1> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(count - 1)}>Decrement</button> <button onClick={() => setCount(0)}>Reset</button> </div> ); }; export default Counter;

In this code, we import React and useState for managing the component's state. The Counter function defines our UI, featuring buttons to increment, decrement, and reset the counter.

Using the Counter Component

Now, let's use this counter in our main application. Open src/App.js and modify it like so:

import React from 'react'; import './App.css'; import Counter from './components/Counter'; function App() { return ( <div className="App"> <h1>Welcome to My Simple React App</h1> <Counter /> </div> ); } export default App;

Here, we imported our Counter component and included it in the main App component.

Managing Global State

In more complex applications, you might need to manage state that can be accessed by multiple components. For this, you can use context or a global state management library like Redux. For simplicity, we will use the React Context API.

Creating a Global State with Context API

  1. Create a file named GlobalState.js inside the src/ directory:
import React, { createContext, useState } from 'react'; export const GlobalContext = createContext(); export const GlobalProvider = (props) => { const [counter, setCounter] = useState(0); return ( <GlobalContext.Provider value={{ counter, setCounter }}> {props.children} </GlobalContext.Provider> ); };

This file exports a GlobalContext and a GlobalProvider which sets the global state for our counter.

Wrapping the Application with GlobalProvider

Next, wrap your App component with GlobalProvider. Edit your src/index.js to look like this:

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import { GlobalProvider } from './GlobalState'; ReactDOM.render( <GlobalProvider> <App /> </GlobalProvider>, document.getElementById('root') );

Using the Global State in Components

Now, we can use the global state inside any component. Let’s modify the Counter component to utilize the global state instead:

import React, { useContext } from 'react'; import { GlobalContext } from '../GlobalState'; const Counter = () => { const { counter, setCounter } = useContext(GlobalContext); return ( <div style={{ textAlign: 'center', marginTop: '20px' }}> <h1>Counter: {counter}</h1> <button onClick={() => setCounter(counter + 1)}>Increment</button> <button onClick={() => setCounter(counter - 1)}>Decrement</button> <button onClick={() => setCounter(0)}>Reset</button> </div> ); }; export default Counter;

Now, the Counter component pulls the counter state from our global context.

Conclusion

With what you’ve learned in this blog post, you should have a solid foundation to build simple React applications, create reusable components, and manage state effectively. As you continue to explore React, you'll discover many advanced topics like routing, performance optimization, and integration with back-end services. Happy coding!

Popular Tags

ReactJavaScriptWeb Development

Share now!

Like & Bookmark!

Related Collections

  • Mastering React Concepts

    24/08/2024 | ReactJS

  • React Interview Challenges: Essential Coding Problems

    14/09/2024 | ReactJS

Related Articles

  • Testing React Components with Jest and React Testing Library

    24/08/2024 | ReactJS

  • Forms in React: Handling User Input

    24/08/2024 | ReactJS

  • Understanding Conditional Rendering in React

    24/08/2024 | ReactJS

  • Differences Between the DOM, Shadow DOM, and Virtual DOM

    21/07/2024 | ReactJS

  • Understanding Kotlin Higher-Order Functions

    28/07/2024 | ReactJS

  • Understanding React Suspense

    16/07/2024 | ReactJS

  • Understanding React JS

    28/11/2024 | ReactJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design