"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

The embedded Google iframe is causing unnecessary padding at the bottom of the page

Below is a snippet of HTML code: <div class="google-maps"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d109782.8671228349!2d76.62734023564995!3d30.69830520749905!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x390fee90 ...

Place CSS elements in relation to the underlying element

This is an example of my HTML structure: <nav id="menu"> <ul> <li><a href="">Products</a></li> <li><a href="">Offers</a></li> <li><a href="">References</a>& ...

Ensuring the accuracy of data sent to an API server through a POST request from an app

As I delve into building a React.js application that communicates with an API server, I've searched through numerous articles on simulating these calls and generating fake responses from the API. Utilizing @testing-library/react for testing comes easi ...

Adjust the content to expand and occupy the entire height using Material UI cut-off Drawer

I am using the provided Material UI code for a persistent clipped drawer, but I am encountering an issue with the content height. I have set the background of the content section to red in my demo sandbox to showcase the problem. My goal is for the content ...

Difficulties encountered while attempting to modify a class using Javascript

Recently, I've encountered an issue with my JavaScript where I am unable to keep a particular element's class changed. Despite attempting to change the class to "overlist", it only stays that way briefly before switching back to its original stat ...

I was baffled by the sudden closure of the connection and couldn't determine the reason behind it

While trying to post data to the wordpress api, I encountered an issue with a closed connection. It was working initially, but now I'm unsure of what went wrong. handleSignIn = () => { const post = { "email" : this.state.email, ...

What CSS property prevents a fixed header from overlapping a scrolled element?

After creating a fixed header for my HTML table, I noticed that as I scroll down the page, everything is being overlapped by the fixed header except for one slider (noUiSlider). I am curious to know which CSS property is preventing the header from overlayi ...

Using force-directed layout to access and retrieve specific data from external or internal data sources

Just starting out with d3js and currently working on modifying the Force directed layout found at http://bl.ocks.org/mbostock/1153292 I have managed to make it so that when I hover over the node circles, the corresponding source value filenames should app ...

In what situations is it essential to utilize the `rerender` function in the React Testing Library?

In the past, my team and I usually focused on writing React Testing Library (RTL) tests for the main parent components that contained numerous nested child components. This approach made sense and proved to be effective. The child components in question we ...

Struggling to eliminate margins in a React web application

Can anyone assist me with removing the large white margins on my react project? Here are some solutions I have attempted. * { margin: 0; padding: 0; } /-/-/-/ body { max-width: 2040px; margin: 0 auto; padding: 0 5%; clear: both; } I've exp ...

Struggling to activate the link:hover transformation

At this link, you can find an example of using CSS transform to rotate links on hover, but I'm having trouble getting it to work as expected. <!DOCTYPE html> <html> <head> <style> a:hover{ ...

Enhancing the SVG font size through custom CSS styling

Working with an SVG element and utilizing CSS to adjust the font-size of the text within the SVG. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720"> <rect class="vBoxRect" width="1280" height="720" fill="none" stroke="red"& ...

Encountering an error in React when attempting to convert a class component to a function

As I've been converting my class components to functions, I encountered a hook error related to my export default. Although I believe it's a simple issue, I can't seem to find the solution I need. The following code is where the error occur ...

GSAP TimelineLite is not being loaded correctly by NPM and Webpack

We are currently in the process of refining and optimizing a production application by cleaning up and organizing dependencies. Within our React component, we utilize GSAP for transitions, specifically only requiring the TimelineLite library. Since our an ...

After refreshing the page, the console log within the React useEffect function ceases to function

Incorporating the 'useEffect' function to fetch data and store it in the 'ratings' array has proven successful. However, there seems to be an issue when attempting to iterate through the elements of the 'ratings' array for log ...

Employing bootstrap to include oversized images within a compact, fixed div

I am facing an issue with image responsiveness in the middle row of my layout. Despite using Bootstrap 4 and applying classes like img-fluid, the images in my #fullColumn area do not resize properly. The images are dragged into this area by users and are ...

What techniques can I use to ensure that my website's layout adjusts correctly when resized?

body { padding: 0; margin: 0; font-family: 'Roboto', sans-serif; font-size: 16px; box-sizing: border-box !important; } a { display: flex; justify-content: center; align-items: center; width: 100%; height: 100%; text-decorat ...

Gatsby: Retrieving JSON data following the initial loading of the page

As I embark on my first PWA project using Gatsby, I am faced with a 3mb json file containing an array of objects. The main functionality of this app is to allow users to search for two objects within the json file (by name or alias) and retrieve all relate ...

What is the proper way to create a React Context in TypeScript that accepts both a ref and a setState function as arguments?

When encountering various errors, one of them being: Type 'Dispatch<SetStateAction<null>>' is not assignable to type '() => void' My code looks something like this: import React, { ReactElement, ReactNode, useEffec ...

Accordions housing Bootstrap 3 pills in a sleek design

I'm working on integrating pills and an accordion in Bootstrap 3. Everything seems to be functioning correctly, but there are a couple of issues I am encountering: When the accordion is open, clicking on another tab closes the accordion. I would li ...