Build a Simple React JS Interactive Web-Based Feedback Form with Stars: A Beginner’s Guide

In the digital age, gathering feedback is crucial for understanding user experiences and improving products or services. Whether you’re building a website, an application, or even just offering an online service, knowing what your users think can be invaluable. A well-designed feedback form can be a powerful tool for collecting this information. In this tutorial, we’ll dive into building a simple, yet effective, interactive feedback form using React JS. This form will feature a star rating system, allowing users to quickly and easily express their satisfaction level. We’ll cover everything from setting up your React environment to handling user input and displaying the collected data. This project is ideal for beginners and intermediate developers looking to enhance their React skills and create interactive web components.

Why Build a Feedback Form?

Feedback forms serve multiple purposes. They help you:

  • Understand User Satisfaction: Gauge how users feel about your product or service.
  • Identify Areas for Improvement: Pinpoint specific features or aspects that need attention.
  • Gather Valuable Insights: Collect qualitative data through open-ended questions.
  • Improve User Experience: Make informed decisions to enhance the overall user experience.

React JS is an excellent choice for building feedback forms due to its component-based architecture, which allows for creating reusable and maintainable UI elements. The star rating system provides a visual and intuitive way for users to rate their experience, making the feedback process quick and engaging.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js and npm (or yarn): You’ll need Node.js and npm (Node Package Manager) or yarn to manage project dependencies. You can download them from https://nodejs.org/.
  • A Code Editor: A code editor like Visual Studio Code, Sublime Text, or Atom will be helpful.
  • Basic Understanding of HTML, CSS, and JavaScript: Familiarity with these web technologies is essential for understanding the code.

Setting Up Your React Project

Let’s start by creating a new React project using Create React App. Open your terminal and run the following command:

npx create-react-app feedback-form-with-stars

This command creates a new directory called feedback-form-with-stars with all the necessary files to get your React application up and running. Once the project is created, navigate into the project directory:

cd feedback-form-with-stars

Now, start the development server:

npm start

This will open your React app in your default web browser, usually at http://localhost:3000. You should see the default React app’s welcome screen. We’ll now modify the src directory to build our feedback form.

Project Structure

Here’s how we’ll structure our project:

  • src/App.js: This will be our main component, handling the overall structure of the feedback form and managing the state.
  • src/components/StarRating.js: This component will handle the star rating functionality, rendering the stars and handling user interaction.
  • src/App.css: This file will contain the CSS styles for the form and star rating.

Creating the Star Rating Component

Let’s create the StarRating.js component. This component will display the stars and allow the user to select a rating. Create a new file named StarRating.js inside a folder called components in your src directory.

Here’s the code for StarRating.js:

// src/components/StarRating.js
import React, { useState } from 'react';
import '../App.css'; // Import your CSS file

const StarRating = ({ onStarClick }) => {
  const [rating, setRating] = useState(0);
  const [hover, setHover] = useState(0);

  const handleStarClick = (selectedRating) => {
    setRating(selectedRating);
    onStarClick(selectedRating);
  };

  return (
    <div>
      {[...Array(5)].map((_, index) => {
        const starValue = index + 1;
        return (
          <button
            key={starValue}
            className={starValue  handleStarClick(starValue)}
            onMouseEnter={() => setHover(starValue)}
            onMouseLeave={() => setHover(0)}
          >
            ★ {/* Unicode character for a filled star */}
          </button>
        );
      })}
    </div>
  );
};

export default StarRating;

Let’s break down this code:

  • Import Statements: We import React and useState from ‘react’. We also import the css file for styling.
  • State Variables:
    • rating: Stores the currently selected star rating (0-5). It’s initialized to 0.
    • hover: Stores the value of the star the user is hovering over.
  • handleStarClick Function: This function is called when a star is clicked. It updates the rating state and calls the onStarClick prop, passing the selected rating.
  • JSX Structure:
    • We use ★ for the filled star character.
    • We map over an array of length 5 to create 5 star buttons.
    • Each button has an onClick event handler that calls handleStarClick.
    • Each button also has onMouseEnter and onMouseLeave event handlers to handle the hover effect.
    • The className of each button is dynamically set based on whether the star should be filled (filled class) or not.

Building the Main App Component

Now, let’s modify App.js to include the StarRating component and handle the form submission. Replace the contents of src/App.js with the following code:

// src/App.js
import React, { useState } from 'react';
import StarRating from './components/StarRating';
import './App.css';

function App() {
  const [rating, setRating] = useState(0);
  const [comment, setComment] = useState('');
  const [submitted, setSubmitted] = useState(false);

  const handleStarClick = (selectedRating) => {
    setRating(selectedRating);
  };

  const handleCommentChange = (event) => {
    setComment(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    // In a real application, you would send this data to a server
    console.log('Rating:', rating);
    console.log('Comment:', comment);
    setSubmitted(true);
  };

  return (
    <div>
      {submitted ? (
        <div>
          <h2>Thank you for your feedback!</h2>
          <p>We appreciate your input.</p>
        </div>
      ) : (
        
          <h2>Feedback Form</h2>
          <p>How would you rate your experience?</p>
          
          <label>Any other comments?</label>
          <textarea id="comment" name="comment" />
          <button type="submit" disabled="{rating">
            Submit Feedback
          </button>
        
      )}
    </div>
  );
}

export default App;

Here’s what’s happening in App.js:

  • Import Statements: We import React, useState, StarRating component, and the css file.
  • State Variables:
    • rating: Stores the selected star rating.
    • comment: Stores the user’s comment from the text area.
    • submitted: A boolean that tracks whether the form has been submitted.
  • handleStarClick Function: Updates the rating state when a star is clicked.
  • handleCommentChange Function: Updates the comment state when the text area value changes.
  • handleSubmit Function:
    • Prevents the default form submission behavior.
    • Logs the rating and comment to the console (in a real application, you’d send this data to a server).
    • Sets the submitted state to true.
  • JSX Structure:
    • Conditionally renders either the feedback form or a thank you message based on the submitted state.
    • The form includes:
      • A heading and a descriptive paragraph.
      • The StarRating component.
      • A text area for comments.
      • A submit button (disabled if no rating is selected).

Styling the Application (App.css)

To make our feedback form look good, we’ll add some CSS styles. Create the file src/App.css if you haven’t already and add the following code:

/* src/App.css */
.App {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
}

.feedback-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  width: 400px;
}

.feedback-form h2 {
  margin-bottom: 15px;
  color: #333;
}

.feedback-form p {
  margin-bottom: 10px;
  color: #555;
}

.star-rating {
  display: flex;
  margin-bottom: 15px;
}

.star {
  font-size: 2rem;
  color: #ccc;
  border: none;
  background: none;
  padding: 0;
  cursor: pointer;
  transition: color 0.2s;
}

.star.filled {
  color: #ffc107;
}

.star:hover {
  color: #ffc107;
}

.comment-textarea {
  width: 100%;
  padding: 10px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
  resize: vertical;
}

.submit-button {
  background-color: #4caf50;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.submit-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.thank-you-message {
  text-align: center;
}

This CSS provides basic styling for the form, stars, text area, and submit button. It also includes styles for the thank you message.

Running and Testing Your Application

Save all the files. Then, in your terminal, make sure your development server is still running (npm start). Open your browser to http://localhost:3000. You should see your feedback form! Test the following:

  • Star Rating: Click on the stars to select a rating. The stars should fill in as you hover over them and click.
  • Comment Area: Type in a comment.
  • Submit Button: The submit button should be disabled until you select a star rating. Once you select a rating, the button should become enabled. Clicking the submit button should display the “Thank you” message and log the rating and comment to the browser’s console.

Common Mistakes and Troubleshooting

Here are some common mistakes and how to fix them:

  • Incorrect File Paths: Double-check that your file paths in the import statements are correct. For example, if StarRating.js is in a different folder, you’ll need to adjust the import path in App.js.
  • CSS Not Applied: Ensure you’ve imported your CSS file correctly in both App.js and StarRating.js. Also, make sure the CSS file name matches the import statement.
  • State Not Updating: Verify that your state variables (rating, comment) are being updated correctly using setRating and setComment. Check the console for any errors.
  • Button Not Disabling: Make sure the submit button’s disabled attribute is correctly bound to the rating state (disabled={rating === 0}).
  • Missing Dependencies: If you encounter errors about missing modules, ensure you have run npm install or yarn install to install all necessary dependencies.

Enhancements and Next Steps

This is a basic feedback form. Here are some ways you can enhance it:

  • Server Integration: Instead of logging the data to the console, integrate with a backend server (e.g., using Node.js, Express, or a serverless function) to store the feedback in a database.
  • Validation: Add form validation to ensure users provide required information.
  • Error Handling: Implement error handling to gracefully handle server errors or other issues.
  • More Input Fields: Add more input fields (e.g., email, name) to collect more user information.
  • Styling: Customize the CSS to match your website’s design. Use a CSS framework like Bootstrap or Tailwind CSS to speed up styling.
  • Accessibility: Ensure the form is accessible by using semantic HTML and ARIA attributes for screen readers.
  • Real-time Feedback: Use WebSockets to provide real-time feedback to the user after submission.

Key Takeaways

Building an interactive feedback form in React JS is a great way to learn about component-based architecture, state management, and handling user input. The star rating component provides an intuitive way for users to provide feedback. This tutorial provides a solid foundation for building more complex forms and integrating them into your web applications. Remember to break down the problem into smaller, manageable components, and always test your code thoroughly. By following these steps, you can create a user-friendly and effective feedback mechanism for your projects.

As you continue to develop your React skills, the ability to create dynamic and interactive UI elements like this feedback form will become increasingly valuable. Understanding how to manage state, handle user interactions, and structure your application into reusable components are key principles in React development. Experiment with different features, explore advanced styling techniques, and most importantly, practice. Each project you undertake will solidify your understanding and allow you to build increasingly sophisticated and engaging web applications. Remember that the journey of a thousand miles begins with a single step, and the journey of mastering React begins with building a simple feedback form.