How to modify the styling of an input element in React without directly manipulating the input itself

I have collected responses from a survey I created and now I want to showcase the results.
The responses are rated on a scale from 1 to 5, and I would like to display them similar to the screenshot.
Each number should be presented within a square, with the selected response highlighted in a different color.
However, I am facing a challenge.
How can I compare the fetched rating with the value of my input?
Since I am not using onChange, I cannot rely on event.target.value.

I wish to achieve something like this:

className={`square ${element.answer===value && "red"}`}

Below is an excerpt of my code:

import React, { useEffect, useState } from "react";
import "./index.css";
import axios from "axios";

/* import icons */
import FileWhite from "../../assets/img/file-text-white.svg";
import StarWhite from "../../assets/img/star-white.svg";
import Minus from "../../assets/img/minus.svg";

const Responses = ({ id }) => {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
    if (id) {
      const fetchData = async () => {
        try {
          const response = await axios.get(
            `http://localhost:3001/responses/${id}`
          );
          console.log(response.data);
          setData(response.data);
          setIsLoading(false);
        } catch (error) {
          console.log(error.message);
        }
      };
      fetchData();
    }
  }, [id]);

  return isLoading ? (
    <div>Loading...</div>
  ) : (
    <div id="responses">
      {data.map((responses) => {
        return responses.answers.map((element) => {
          return (
            <article>
              <div className="question">
                <div
                  className={`type ${
                    element.type === "texte" ? "orange" : "red"
                  }`}
                >
                  <span>{element.type === "texte" ? "1" : "2"}</span>
                  <img src={Minus} alt="" />
                  <img
                    src={element.type === "texte" ? FileWhite : StarWhite}
                    alt=""
                  />
                </div>
                <div>{element.question}</div>
              </div>
              {element.type === "texte" ? (
                <div className="answerText">{element.answer}</div>
              ) : (
                <div className="answerNote">
                  <div className="square">
                    <input type="radio" id="note1" name="note" value="1" />
                    <label htmlFor="note1">1</label>
                  </div>

                  <div className="square">
                    <input type="radio" id="note2" name="note" value="2" />
                    <label htmlFor="note2">2</label>
                  </div>

                  <div className="square">
                    <input type="radio" id="note3" name="note" value="3" />
                    <label htmlFor="note3">3</label>
                  </div>

                  <div className="square">
                    <input type="radio" id="note4" name="note" value="4" />
                    <label htmlFor="note4">4</label>
                  </div>

                  <div className="square">
                    <input type="radio" id="note5" name="note" value="5" />
                    <label htmlFor="note5">5</label>
                  </div>
                </div>
              )}
            </article>
          );
        });
      })}
    </div>
  );
};

export default Responses;

How can I extract the input value to achieve the desired output? (refer to screenshot) https://i.sstatic.net/6RYxE.png

Answer №1

the desired outcome should resemble this

styleName={`block ${element.response ===criteria ? "crimson" : "" }`}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Look for a text containing a unique character

I am facing a problem with searching a string that contains special characters. For example: keyword = alpha#bet+a db.collection.find('course.title': { $regex: keyword, $options: 'i' } ) However, I keep encountering errors such as &a ...

The right-floating div element is not displaying horizontally; instead, it is breaking into a new line

My issue is the dynamically added div elements are not displaying horizontally within a container div element with a specific width. They always break into a new line. Below is the code snippet I am using: var i=1; $(document).ready(function () { ...

Activate SVG graphics upon entering the window (scroll)

Can anyone assist me with a challenging issue? I have numerous SVG graphics on certain pages of my website that start playing when the page loads. However, since many of them are located below the fold, I would like them to only begin playing (and play onc ...

Enhance your Next.js application by including the 'style' attribute to an element within an event listener

I am currently trying to add styles to a DOM element in Next.js using TypeScript. However, I keep getting the error message "Property 'style' does not exist on type 'Element'" in Visual Studio Code. I have been unable to find an answer ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

What steps can be taken to create a progress bar in the input field that spans the entire width of its parent div, reaching

I received assistance from a friend in creating this progress bar. Everything seems to be working well, except for the fact that the progress bar is not extending to the full width of the parent div. The new width after each input tag is entered using Java ...

Picking out specific elements from a component that is rendered multiple times in a React application

One of the challenges I face involves a component called card, which is rendered multiple times with different data. Here's how it looks: { this.state.response.reminders.map((item,i=0) =>{ return <Card key={i++} reminder={item} deleteRem={th ...

Transitioning images while hovering over a different element

Need some inspiration for a school project? I'm stuck on how to create a smooth image fade effect in CSS when hovering over another element (like an anchor link) on the same page. I've been attempting to use the :target and not(:target) selector ...

Styling Material-UI Icons in React Using Style Mapping

What is the most efficient way to apply the same style to multiple material-ui icon elements without individually styling each object? const btns = [ { name: "test1", icon: <Icon1 />, link: "test1" }, { name: "test2", icon: <Icon2 />, li ...

Tips for determining if a React app is being accessed in a web browser or on a mobile device

I am working with a react web application and an IOS app (web view). I am looking to incorporate some additional features into the IOS app. Is there a method available to identify whether the app is being accessed through a web browser or on a mobile dev ...

Loading images in advance using JavaScript

I have been searching through multiple forums and cannot seem to figure out the issue. The problem I am encountering is related to a website where there are three images with a hover effect. When the page first loads, there is a delay in loading the backgr ...

On mobile devices, the Next.JS application (featuring Chakra UI) does not stretch to full width

I'm stumped on this one... Maybe there's something simple I'm overlooking, but I'm hoping for some help from you guys. When viewed on mobile devices, the entire HTML element takes up around 80% of the screen width. Oddly enough, resiz ...

After a single click, the functionality of jquery.nav.js seems to be malfunctioning

Encountering an error message: Uncaught TypeError: Cannot read property 'top' of undefined(…) jquery.nav.js:183 In an effort to convert my web app into a Single Page Application (SPA) using the jquery.nav.js library (available at https://githu ...

Ways to resolve the recurring npm ERR! code that appears whenever I enter npm start in the terminal

As I work on creating an application in React, I encountered an issue when trying to run "npm start" in the command line. The error message I received is shown below: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path /Users/a1234/Downloads/meditati ...

The integration between React.js, Node.js, and Express.js is facing issues with the socket.io functionality

I am currently working on integrating socket.io with React.js, running the socket.io on a backend server using Express.js. One issue I am facing is that when an order is placed on the homepage, it should be displayed in real-time on the Orders page in Rea ...

Is there a way to retrieve data from two separate calls to MongoDB and then pass it to a child component?

I am developing an application where users can save their favorite rental assets and view them on a page called favorites. class Favorites extends Component { state = { cards: [], }; async componentDidMount() { const { data } = await u ...

Learn the best practices for incorporating jQuery and other JavaScript libraries in your Angular2 projects

Is it possible to integrate a demo showcasing Bootstrap carousel with CSS3 animations in Angular2 using HTML, CSS, and JS? I have created my own implementation in Plunker with Angular2, but I am facing issues with the animated inner content of the carousel ...

Struggles with arranging HTML header components

I've been attempting to insert a Twitter logo into the header of my website (which is styled using Bootstrap CSS), but unfortunately, it's causing some alignment issues. My initial goal was to position them next to each other, however, they ended ...

What is the best way to trigger form submission when the value of an input element changes?

I am currently developing a website using Bootstrap and I am exploring the idea of incorporating a toggle button to alter the color scheme by simply toggling it. I have successfully created a toggle button similar to a checkbox, but now I am looking for ...

How can you center a div at the top of another div?

I am working with a nested div structure and trying to center the inner content of one div within another. Is it possible to achieve this using CSS? <div id="outer"> bla, bla....... <div id="inner"> <p>Test</p> </div> ...