"Implementing a form submission feature in React.js that dynamically applies a class to the result element

I recently developed a basic BMI calculator using React.js. I am now attempting to implement a feature where if the calculated BMI result falls outside the range of a healthy BMI, the result text will be displayed in red color (I am utilizing styled-components for this purpose). However, I am facing challenges determining the appropriate location to integrate this functionality, whether within the Form or Result component, and what methodologies to employ (I reviewed the classNames library but found it difficult to grasp based on the provided examples). Any guidance from fellow developers would be greatly appreciated.

Form element

 // Code for Form component...

Result element

// Code for Result component...

Thank you in advance for any assistance you can provide.

Answer №1

Consider incorporating an additional useState hook to manage a danger state:

    const [danger, setDanger] = useState(false);

Then, if the result indicates an unhealthy BMI, update the danger state to true:

    if (classification !== "Healty") {
        setDanger(true);
    } else {
        setDanger(false);
    }

Finally, customize the styling based on the value of the danger state:

    let component = null;
    
    danger 
    ? 
        component = <Result className="redStyled" ...props />
    :
        component = <Result className="healthyStyled" ...props />
    

You could also consider utilizing styled-components and passing a prop such as isHealhty to the Result component for conditional rendering based on health status.

Answer №2

To start, establish a new class and utilize setState to keep the code up-to-date.

const [category, setCategory] = useState(0);

Within your decision-making code, assign the class accordingly. You have the freedom to use your own codes or strings, but for this example, numbers are used.

if (bmi < 18.5) {
      setClassification("Underweight");
      setCategory(1);
    } else if (bmi > 18.5 && bmi <= 24.9) {
      setClassification("Healthy");
      setCategory(2);
    } else if (bmi > 24.9 && bmi < 30) {
      setClassification("Pre-obesity");
      setCategory(3);
    } else if (bmi < 35) {
      setClassification("Obesity class I");
      setCategory(4);
    } else if (bmi < 40) {
      setClassification("Obesity class II");
      setCategory(5);
    } else {
      setClassification("Obesity class III");
      setCategory(6);
    }

Include the category as a prop in the result component

<Result bmi={bmi} classification={classification} category={category} />

Subsequently, inspect the result component and tailor the design of the component to match

const Result = ({ bmi, classification, category }) => {
  const styles = [{'style of 1'},{'style of 2'},{'style of 3'},{'style of 4'},{'style of 5'},{'style of 6'}];
  return (
    <StyledResultWrapper style={styles[category]}>
      <StyledResult>{bmi && <>Your BMI is {bmi}</>}</StyledResult>
      <StyledResult>{classification}</StyledResult>
    </StyledResultWrapper>
  );
};
export default Result;

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

Error: An issue occurred when trying to access a property while passing in a prop

Encountering an issue with my Timeline.js file Receiving a TypeError: Cannot read property 'year' of undefined when passing a prop to a React component. The goal is to extract a specific variable from the prop. In this case, timelineYears.js con ...

Twilio SDK integration for reply extensions featuring a customized dial pad functionality

Currently, I am developing a call-based application using Twilio SDK along with React and Node.js. My main requirement is as follows: During any incoming or outgoing audio call within the system, I need to provide users with access to a number pad button. ...

What is the best way to ensure that my image completely occupies the div?

I am facing a challenge in creating a hero image that would completely fill the div on my webpage. Despite setting the width and height to 100%, the image seems to only occupy half of the space. Check out the CSS and HTML code snippet here. div.hero{ ...

What causes the image to not appear at the center bottom of the page when using IE for loading?

Why does the loading image not appear at the center bottom of the page in IE? This function loads content when the page is loaded and also loads content when scrolled to the bottom. When you load the page index.php, you will see the loading image at the ...

How can I trigger an audio element to play using onKeyPress and onClick in ReactJS?

While attempting to construct the Drum Machine project for freeCodeCamp, I encountered a perplexing issue involving the audio element. Despite my code being error-free, the audio fails to play when I click on the div with the class "drum-pad." Even though ...

Transmit data from list items in the HTML to a form

Based on my understanding, there are limited options available to style an <option> tag within a <select> dropdown and it appears quite plain. So I was thinking about creating a more visually appealing dropdown using <ul> <li> tags ...

When the enter key is pressed in a contenteditable div, line breaks are disregarded

Is there a way to ensure that when the return key is pressed to start a new line for a post, the output actually starts on a new line? I've been having trouble with this and would like to know the most common solution. Check out the demo below for te ...

What is the correct way to include '?i#efix' in a font directory path in a Rails application?

It is suggested to include ?#iefix at the end of .eot font paths in order to resolve another erratic behaviour issue in IE: @font-face { font-family: 'MyWebFont'; src: url('webfont.eot'); /* IE9 Compat Modes */ src: url(&ap ...

What is the best way to connect the "areaName" with the <TextBox> attributes value="" and onChange=""?

After calling an API and mapping the array, I have successfully bound the data on <TableCell> {this.state.allArea.map((allArea, i) => ( <TableRow > <TableCell >{allArea.areaName}</TableCe ...

Oops! Looks like there was a problem: setShowCatMenu function is not defined

While attempting to solve a problem, I encountered an error where the setShowCatMenu is not recognized as a function type. Check out the code snippet below: Menu.jsx import React from 'react'; import Link from 'next/link'; import { BsCh ...

Ways to center a spinner on the screen using CSS during loading

Upon loading the page, my spinner appears in the center of the screen after a second. However, in the initial frame of the page, it is not centered but positioned on the top-left corner instead. How can I ensure that my spinner starts off centered from the ...

Issue encountered while utilizing a MUI select component to display the correct element

I'm facing a challenge in a small "learning" project I'm currently working on. Just to give some background, I'm using React with Typescript. The goal is to implement a select element that, upon choosing an option, will display the corresp ...

Is it possible to place a div and a heading side by side within the same line?

Is there a way to align a div and header on the same line? Currently, the red div is displaying below the text. Thank you for your help! .underlined { border-bottom: 1px dotted #000; text-decoration:none; } .block { height:15px; background-color: #ff505 ...

Exploring the World of Print CSS, Embracing Bootstrap, and Master

In continuation of my previous query, I am facing an issue with setting up a filemaker foreach loop to display a group of images along with their names and IDs, accompanied by checkboxes. Upon checking the relevant checkboxes, the corresponding images are ...

When using the e.target.getAttribute() method in React, custom attributes may not be successfully retrieved

I am struggling with handling custom attributes in my changeHandler function. Unfortunately, React does not seem to acknowledge the custom "data-index" attribute. All other standard attributes (such as name, label, etc.) work fine. What could be the issu ...

I was able to resolve the fixed position issue of a button on Safari for iPhone 3G

Here is the setup I have on jsfiddle: http://jsfiddle.net/zZDqH/ Currently, there is a button fixed at bottom:0px. You can scroll up and down the page, and the button will stay at the bottom of the page. However, when testing in Safari on an iPhone 3G ( ...

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

A request sent from a react.js frontend is being processed as a GET request on a node

My POST request seems to be getting converted to a GET request somewhere in my REACT client code. Here is the react code snippet: function SavePatient(event) { event.preventDefault(); console.log("Saving Patient Data"); console.log(patient ...

What is the best way to store a small number of files in the state

I have recently implemented Drag and Drop functionality, and now I am facing an issue where I need to save a few files in state. const [uploadedFiles, setUploadedFiles] = useState<any[]>([]); const onDropHandler = async (e: React.DragEvent<HTMLDi ...