react projects for beginners with source code

React Projects For Beginners With Source Code

React is a popular JavaScript library for building user interfaces. It allows developers to create reusable components and manage the state of an application. React projects for beginners with source code can help you learn the basics of React while building fun and interactive applications.

1. Simple Counter

A simple counter is a classic beginner React project that allows you to learn how to create and manage state in a React application. The counter app displays a number on the screen, which increases or decreases when the user clicks a button.

To create a simple counter app, you can start by creating a new React component that displays a number and two buttons. The number can be stored in the state of the component, and the buttons can call a function that updates the state of the component.

Once you have created the basic structure of the app, you can add some styling to make it look more visually appealing.

Here is an example of a simple counter app with a small explanation afterwards.

import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount(count + 1);
  };

  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h1>Counter App</h1>
      <p>Count: {count}</p>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
    </div>
  );
}

export default Counter;

In this code, we have used the useState hook to define the count state and the setCount function to update the state. We have also defined two functions increment and decrement to update the state based on the button click. Finally, we have rendered the current count and two buttons to increment and decrement the count.

2. Quiz App

A quiz app is another beginner React project that can help you learn how to manage state and create dynamic user interfaces. The quiz app allows the user to answer a series of questions and displays the user’s score at the end.

To create a quiz app, you can start by creating a JSON file that contains the questions and answers for the quiz. You can then create a React component that reads the data from the JSON file and displays the questions one at a time.

As the user answers each question, the component can update the state to keep track of the number of correct answers. When the quiz is complete, the component can display the user’s score and give the user the option to restart the quiz.

Below is an example of a basic quiz app created in React. Feel free to take this code and expand how you see fit.

import React, { useState } from 'react';

const questions = [
  {
    question: 'What is the capital of France?',
    options: ['Paris', 'London', 'Berlin', 'Madrid'],
    answer: 'Paris'
  },
  {
    question: 'What is the largest country in the world?',
    options: ['China', 'United States', 'Russia', 'Canada'],
    answer: 'Russia'
  },
  {
    question: 'What is the tallest mountain in the world?',
    options: ['Kilimanjaro', 'Everest', 'Denali', 'Aconcagua'],
    answer: 'Everest'
  }
];

function Quiz() {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [score, setScore] = useState(0);
  const [showScore, setShowScore] = useState(false);

  const handleAnswerOptionClick = (answer) => {
    if (answer === questions[currentQuestion].answer) {
      setScore(score + 1);
    }

    const nextQuestion = currentQuestion + 1;
    if (nextQuestion < questions.length) {
      setCurrentQuestion(nextQuestion);
    } else {
      setShowScore(true);
    }
  };

  return (
    <div className="quiz">
      {showScore ? (
        <div className="score-section">
          You scored {score} out of {questions.length}
        </div>
      ) : (
        <>
          <div className="question-section">
            <div className="question-count">
              <span>Question {currentQuestion + 1}</span>/{questions.length}
            </div>
            <div className="question-text">{questions[currentQuestion].question}</div>
          </div>
          <div className="answer-section">
            {questions[currentQuestion].options.map((option) => (
              <button onClick={() => handleAnswerOptionClick(option)}>{option}</button>
            ))}
          </div>
        </>
      )}
    </div>
  );
}

export default Quiz;

In this code, we have defined an array of questions with their options and correct answers. We use the useState hook to define the currentQuestion state, the score state, and the showScore state.

The handleAnswerOptionClick function is called when the user clicks an answer option. It checks if the answer is correct and updates the score state. If there are more questions, it moves to the next question by updating the currentQuestion state. If there are no more questions, it sets showScore to true.

Finally, we render the current question, the answer options, and the score (if showScore is true).

3. Weather App

A weather app is a beginner React project that can help you learn how to use APIs and handle asynchronous data. The weather app allows the user to enter a city or zip code and displays the current weather for that location.

To create a weather app, you can start by using an API to retrieve the current weather data for a given location. You can then create a React component that allows the user to enter a location and displays the current weather data.

When the user submits the form, the component can make an API call to retrieve the weather data and update the state of the component. The component can then display the weather information on the screen.

The source code for a Weather App that was created using the OpenWeatherMap API. Again, feel free to expand on this starter code and make it your own.

import React, { useState, useEffect } from 'react';

const API_KEY = 'YOUR_API_KEY';

function Weather() {
  const [city, setCity] = useState('');
  const [weather, setWeather] = useState(null);

  useEffect(() => {
    const getWeather = async () => {
      const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}`;
      const response = await fetch(url);
      const data = await response.json();
      setWeather(data);
    };

    if (city) {
      getWeather();
    }
  }, [city]);

  const handleSubmit = (event) => {
    event.preventDefault();
    setCity(event.target.city.value);
  };

  return (
    <div className="weather">
      <h1>Weather App</h1>
      <form onSubmit={handleSubmit}>
        <input type="text" name="city" placeholder="Enter city name" />
        <button type="submit">Get Weather</button>
      </form>
      {weather && (
        <>
          <h2>{weather.name}, {weather.sys.country}</h2>
          <p>{Math.round(weather.main.temp - 273.15)}&deg;C</p>
          <p>{weather.weather[0].description}</p>
        </>
      )}
    </div>
  );
}

export default Weather;

In this code, we have used the useState hook to define the city state and the weather state. We have used the useEffect hook to fetch weather data from the OpenWeatherMap API whenever the city state changes.

When the user submits the form with a city name, it sets the city state to trigger the useEffect hook. Once the weather data is fetched, it sets the weather state.

Finally, we render the form to enter a city name, and if weather state is not null, we render the city name, temperature, and weather description.

4. To-Do List

A to-do list is another beginner React project that can help you learn how to manage state and create dynamic user interfaces. The to-do list app allows the user to add, edit, and delete items from a list of tasks.

To create a to-do list app, start by creating a new React component that displays a list of tasks. The list can be stored in the state of the component. Each task can have a name and a boolean value to indicate whether the task has been completed.

The component can include a form that allows the user to add a new task to the list, and buttons that allow the user to edit or delete existing tasks. As the user interacts with the app, the component can update the state to reflect the changes to the list of tasks.

Below is our react project for beginners with source code tutorial on a simple to do list.

import React, { useState } from 'react';

function TodoList() {
  const [task, setTask] = useState('');
  const [tasks, setTasks] = useState([]);

  const handleSubmit = (event) => {
    event.preventDefault();
    if (task) {
      setTasks([...tasks, task]);
      setTask('');
    }
  };

  const handleDelete = (index) => {
    const newTasks = [...tasks];
    newTasks.splice(index, 1);
    setTasks(newTasks);
  };

  return (
    <div className="todo-list">
      <h1>To-Do List</h1>
      <form onSubmit={handleSubmit}>
        <input type="text" value={task} onChange={(event) => setTask(event.target.value)} placeholder="Enter task" />
        <button type="submit">Add Task</button>
      </form>
      <ul>
        {tasks.map((task, index) => (
          <li key={index}>
            {task}
            <button onClick={() => handleDelete(index)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;

In this code, we have used the useState hook to define the task state and the tasks state. We render a form to enter a task, and on submit, we add the task to the tasks state and clear the task state.

We also map over the tasks state and render a list item for each task. We pass the index of each task to the handleDelete function, which removes the task from the tasks state using the splice method.

Finally, we render a delete button for each task that calls the handleDelete function.

5. Movie Search

A movie search app is a beginner React project that can help you learn how to use APIs. Not only will you learn about APIs but you’ll learn how to handle asynchronous data. The movie search app allows the user to search for movies by title and displays a list of results.

To create a movie search app, you can start by using an API to retrieve the movie data for a given search term. You can then create a React component that allows the user to enter a search term and displays the results.

When the user submits the search form, the component can make an API call to retrieve the movie data. Then you are able to update the state of the component. The component can then display the movie information on the screen.

Here is an example of our react projects for beginners with source code for a movie search project. This project uses the OMDB API.

import React, { useState, useEffect } from 'react';

const API_KEY = 'YOUR_API_KEY';

function MovieSearch() {
  const [query, setQuery] = useState('');
  const [movies, setMovies] = useState([]);

  useEffect(() => {
    const getMovies = async () => {
      const url = `https://www.omdbapi.com/?s=${query}&apikey=${API_KEY}`;
      const response = await fetch(url);
      const data = await response.json();
      if (data.Search) {
        setMovies(data.Search);
      } else {
        setMovies([]);
      }
    };

    if (query) {
      getMovies();
    }
  }, [query]);

  const handleSubmit = (event) => {
    event.preventDefault();
    setQuery(event.target.query.value);
  };

  return (
    <div className="movie-search">
      <h1>Movie Search</h1>
      <form onSubmit={handleSubmit}>
        <input type="text" name="query" placeholder="Search for a movie" />
        <button type="submit">Search</button>
      </form>
      <ul>
        {movies.map((movie) => (
          <li key={movie.imdbID}>
            <img src={movie.Poster} alt={movie.Title} />
            <h2>{movie.Title}</h2>
            <p>{movie.Year}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default MovieSearch;

In this code, we have used the useState hook to define the query state and the movies state. We have used the useEffect hook to fetch movie data from the OMDB API whenever the query state changes.

When the user submits the form with a movie search query, it sets the query state to trigger the useEffect hook. Once the movie data is fetched, it sets the movies state.

Finally, we map over the movies state and render a list item for each movie. We display the movie title, poster, and year.

Conclusion

React projects for beginners with source code can help you learn the basics of React while building fun and interactive applications. By building these projects, you can gain a better understanding of how to create and manage components, handle state and data, and work with APIs.

As you continue to learn and grow as a React developer, you can expand on these projects. You can go on to create more complex and advanced applications. However, starting with these beginner projects can provide a solid foundation for your React journey.

It’s important to note that while source code can be helpful in understanding these projects, it’s beneficial to challenge yourself. It is a good challenge to build the applications without relying on pre-existing code. This will help you to better understand how the different pieces of a React application work together.

Building these react projects can really help you as a developer. It’s also helpful to read through the React documentation and explore different tutorials and resources available online. With time and practice, you can become a confident and skilled React developer.

Are you interested in reading more like this? Check out our latest post on page speed optimization. Leave a comment below if you expanded on any of these react projects for beginners with source code. As always if you have any questions or comments feel free to contact us.

1 thought on “React Projects For Beginners With Source Code”

  1. Pingback: Advantages and Disadvantages of Using CSS Preprocessors in Web Development - Red Surge Technology

Comments are closed.