Beginner React.js Projects to Solidify Your React Skills

Introduction:

Learning React.js isn’t just about theory; hands-on experience is essential. In this blog, we present five beginner-level React projects that help bridge the gap between theory and practice. These projects are key in understanding React’s fundamental concepts. Let’s begin our journey to build practical applications!

As a new developer, you’ve likely faced challenges translating React theory into practice. Some basics may have been unclear from documentation alone. However, as you created your own React applications and sought insights from web searches and video tutorials, you gained valuable experience.

There are so many beginner projects are there. But these five projects represent initial steps in understanding React’s basic concepts for me. They played a pivotal role in building a strong React foundation, serving as a bridge between theory and practical implementation. Join us as we explore these key projects that mark the early stages of my developer career.

1) Stop watch:

The Stopwatch component initializes two state variables: “time” (initially set to 0) for tracking elapsed seconds and “startRunning” (initially false) to control the stopwatch’s state.

Using the useEffect hook, the component starts a timer when “startRunning” becomes true, incrementing “time” by 1 every 0.5 seconds.

The component’s UI includes a “Stopwatch” heading, a paragraph displaying the time, and three buttons: “Start,” “Stop,” and “Reset.”

Code Flow:

  • Start button sets “startRunning” to true, starting the timer.
  • Stop button sets “startRunning” to false, pausing the timer.
  • Reset button sets “time” to 0, effectively resetting the stopwatch.

function Stopwatch() {
  const [time, setTime] = useState<number>(0);
  const [startRunning, setStartRunning] = useState<boolean>(false);

  useEffect(() => {
    if (startRunning) {
      const interval = setInterval(() => {
        setTime(time + 1);
      }, 500);
      return () => clearInterval(interval);
    }
  }, [startRunning, time]);

  return (
    <div>
      <h1>Stopwatch</h1>
      <p>{time} seconds</p>
      <button onClick={() => setStartRunning(true)}>Start</button>
      <button onClick={() => setStartRunning(false)}>Stop</button>
      <button onClick={() => setTime(0)}>Reset</button>
    </div>
  );
}

2) Counter App:

CounterApp is a TypeScript React component that uses the useState hook to manage “count” (starting at 0).

It displays a basic counter app with a heading, a paragraph showing “count,” and two buttons to increase or decrease it.

Button clicks trigger arrow functions to update “count.”


const CounterApp = () => {
  const [count, setCount] = useState<number>(0);

  return (
    <div>
      <h1>Counter App</h1>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
};

3) BMI Calculator:

It defines a BMI Calculator component that allows users to input their height and weight. It then calculates their BMI (Body Mass Index) and displays both the BMI value and a corresponding weight category message. Here’s a more concise and precise overview:

Code Flow:

  • State variables (height, weight, bmi, msg) are initialized using the useState hook.
  • The calculateBMI function computes BMI based on height and weight inputs.
  • BMI is calculated by dividing weight by the square of the height in meters.
  • The weight category message is determined based on the calculated BMI value.
  • State variables (msg and bmi) are updated with the message and BMI value.
  • The handleSubmit function handles form submission, triggering BMI calculation.
  • JSX code renders a form with input fields for height and weight, a submit button, and placeholders for displaying the BMI and weight category.

function BMICalculator() {
  const [height, setHeight] = useState<string>('');
  const [weight, setWeight] = useState<string>('');
  const [bmi, setBMI] = useState<string>('');
  const [msg, setMsg] = useState<string>('');

  const calculateBMI = () => {
    const heightSq = (Number(height) / 100) ** 2;
    const bmiValue = Number(weight) / heightSq;
    let message = '';

    if (bmiValue < 18.5) message = 'Under Weight';
    else if (bmiValue >= 18.5 && bmiValue <= 24.9) message = 'Normal Weight';
    else if (bmiValue >= 25 && bmiValue <= 29.9) message = 'Over Weight';
    else if (bmiValue >= 30) message = 'Obesity';

    setMsg(message);
    setBMI(String(Math.round(bmiValue * 100) / 100));
  };

  const handleSubmit = (e: { preventDefault: () => void }) => {
    e.preventDefault();
    calculateBMI();
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <h2>BMI calculator</h2>
        <div>
          <label>Height (cm)</label>
          <input type="number" value={height} onChange={(e) => setHeight(e.target.value)} />
        </div>

        <div>
          <label>Weight</label>
          <input type="number" value={weight} onChange={(e) => setWeight(e.target.value)} />
        </div>
        <button type="submit">Submit</button>
        <h2>{bmi}</h2>
        <h2>{msg}</h2>
      </form>
    </div>
  );
}

4) Form validation:

It is a simple form validation in a React component. It uses the useState hook to manage the form data and errors. The form has two input fields for email and password, and it checks if these fields are empty when the form is submitted. If any field is empty, it displays an error message below the input field.

Code Flow:

  • The function initializes the form data and errors using the useState hook.
  • The handleChange function is called when the value of an input field changes. It updates the corresponding field in the form data and checks if the value is empty. If it is empty, it sets the error for that field to true.
  • The handleSubmit function is called when the form is submitted. It prevents the default form submission behavior and checks if any of the fields are empty. If any field is empty, it sets the corresponding error to true.
  • The render function returns a form with two input fields for email and password. It also displays an error message below each input field if the field is empty.
  • The input fields and error messages are styled based on the value of the errors state.


export default function FromValidation() {
  const [formData, setFormData] = useState({
    email: '',
    password: '',
  });

  const [errors, setErrors] = useState({
    email: false,
    password: false,
  });

  const handleChange = (e: { target: { name: string; value: string } }) => {
    const { name, value } = e.target;
    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
    setErrors((prevErrData) => ({
      ...prevErrData,
      [name]: Boolean(!value.length),
    }));
  };

  const handleSubmit = (e: { preventDefault: () => void }) => {
    e.preventDefault();
    setErrors((prevErrData) => ({
      ...prevErrData,
      email: Boolean(!formData.email.length),
      password: Boolean(!formData.password.length),
    }));
  };

  return (
    <div>
      <h1>Simple Form Validation</h1>
      <form onSubmit={handleSubmit}>
        <input
          name="email"
          value={formData.email}
          onChange={handleChange}
          placeholder="Email"
          style={{ borderColor: errors.email ? 'red' : 'initial' }}
        />
        {errors.email ? (
          <p style={{ color: errors.password ? 'red' : 'initial' }}>Email is required</p>
        ) : null}
        <input
          name="password"
          value={formData.password}
          onChange={handleChange}
          placeholder="Password"
          style={{ borderColor: errors.password ? 'red' : 'initial' }}
        />
        {errors.password ? (
          <p style={{ color: errors.password ? 'red' : 'initial' }}>Password is required</p>
        ) : null}
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

5) Random joke generator:

This code defines a React component called JokeGenerator that fetches a random joke from an API and displays it on the screen. It also provides a button to fetch another joke.

Code flow:

  • The function initializes two state variables: joke to store the fetched joke and isLoading to track the loading state.
  • The fetchJoke function is defined as an asynchronous function that fetches a joke from the API. It sets isLoading to true, makes a GET request to the API, and stores the fetched joke in the joke state variable.
  • If there is an error while fetching the joke, an error message is logged to the console.
  • Finally, isLoading is set to false to indicate that the joke has been fetched.
  • The useEffect hook is used to fetch a joke when the component is first rendered. It calls the fetchJoke function without any dependencies, so it only runs once.
  • The component returns JSX that displays a heading, a loading message if isLoading is true, or the fetched joke and a button to fetch another joke if isLoading is false.

const JokeGenerator = () => {
  const [joke, setJoke] = useState<string>('');
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const fetchJoke = async () => {
    setIsLoading(true);
    try {
      const response = await fetch(
        'https://v2.jokeapi.dev/joke/Any?blacklistFlags=nsfw,religious,political,racist,sexist,explicit&type=single',
      );
      const data = await response.json();
      setJoke(data.joke);
    } catch (error) {
      console.error('Error fetching joke:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchJoke();
  }, []);

  return (
    <div>
      <h1>Random Joke Generator</h1>
      {isLoading ? (
        <p>Loading...</p>
      ) : (
        <div>
          <p>{joke}</p>
          <button onClick={fetchJoke}>Get Another Joke</button>
        </div>
      )}
    </div>
  );
};

Conclusion:

These beginner React.js projects provide a crucial bridge between theory and practice. By creating a sample apps, you’ve unlocked the power of hands-on learning. Remember, practice is the key to mastering React. Customize and expand these projects to continue your journey toward React expertise.

Happy coding!