Explore three stylish ways to showcase dynamic JavaScript content using CSS

Objective:
For Value 1, the CSS class should be badge-primary
For Value 2, the CSS class should be badge-secondary
For all other values, use the CSS class badge-danger

This functionality is implemented in the handleChange function.

Issue:
Currently, I can only toggle between false and true to apply CSS. This limits me to only two options.
How can I introduce a third option and resolve this issue? Any suggestions?

Details:
*New to reactjs

Stackblitz:
https://stackblitz.com/edit/react-34tdvs?


CSS Styles

h1,
p {
  font-family: Lato;
}

.badge-primary {
  text-align: center;
  color: blue;
}

.badge-danger {
  font-size: 15px;
  color: red;
}

.badge-secondary {
  font-size: 15px;
  color: rgb(0, 204, 255);
}

import React from 'react';
import './style.css';
import React, { Component } from 'react';
import axios from 'axios';

export default class App extends Component {
  constructor() {
    super();

    this.state = {
      isLoaded: false,
      listData: [],
      list2Data: [],
      list3DataRaw: [],
      list3Data: [],
      value: true
    };
  }

  componentDidMount() {
    axios
      .get('https://jsonplaceholder.typicode.com/comments?postId=1')
      .then(response =>
        this.setState({
          isLoaded: true,
          listData: response.data
        })
      );

    axios.get('https://jsonplaceholder.typicode.com/users').then(response =>
      this.setState({
        isLoaded: true,
        list2Data: response.data
      })
    );

    axios.get('https://jsonplaceholder.typicode.com/todos').then(response =>
      this.setState({
        isLoaded: true,
        list3DataRaw: response.data
      })
    );
  }

  handleChange = ({ target }) => {
    // copy current list of items
    const list = [...this.state.list3DataRaw];

    if (1 == target.value) {
      this.setState({
        value: false
      });
    }

    if (1 != target.value) {
      this.setState({
        value: true
      });
    }

    // filter out item being deleted
    const updateList = list.filter(item => item.userId == target.value);

    this.setState({
      list3Data: updateList
    });
  };

  render() {
    const { isLoaded } = this.state;

    const locations =
      this.state.list2Data && 
      this.state.list2Data.map(location => {
        return { value: location.id, label: location.name };
      });

    const locationss =
      this.state.list3Data && 
      this.state.list3Data.map(location => {
        return { value: location.userId, label: location.title };
      });

    //console.log(locations);
    //console.log(locationss);

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <>
          <select
            id="selectLocation"
            value={locations.value}
            onChange={this.handleChange}
          >
            {locations.map(({ value, label }, index) => (
              <option value={value}>{label}</option>
            )}
          </select>

          <select
            id="selectLocationn"
            className={this.state.value ? 'badge-primary' : 'badge-danger'}
            value={locationss.value}
            onChange={this.handleChange}
          >
            {locationss.map(({ value, label }, index) => (
              <option value={value}>{label}</option>
            )}
          </select>

          <table className="table">
            <thead>
              <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody>
              {this.state.listData && 
                this.state.listData.map(item => {
                  return (
                    <tr key={item.id.toString()}>
                      <td>{item.id}</td>
                      <td>{item.name}</td>
                      <td>{item.email}</td>
                    </tr>
                  );
                })}
            </tbody>
          </table>
        </>
      );
    }
  }
}

Answer №1

Below is the current working branch,

https://stackblitz.com/edit/react-dwtfr1

You will find comments within the code explaining the process.

import React from 'react';
import './style.css';
import React, { Component } from 'react';
import axios from 'axios';

export default class App extends Component {
  constructor() {
    super();

    // Made changes to state to optimize data fetching
    this.state = {
      isLoaded: false,
      listData: [],
      list2Data: [],
      selectedlist2DataItem: 1,
      selectedlist3DataItem: 1,
      list3Data: []
    };
  }

  componentDidMount() {
    axios
      .get('https://jsonplaceholder.typicode.com/comments?postId=1')
      .then(response => {
        this.setState({
          ...this.state,
          isLoaded: true,
          listData: response.data
        });
      });

    axios.get('https://jsonplaceholder.typicode.com/users').then(response =>
      this.setState({
        ...this.state,
        isLoaded: true,
        list2Data: response.data.map(location => {
          return { value: location.id, label: location.name };
        })
      })
    );

    axios.get('https://jsonplaceholder.typicode.com/todos').then(response =>
      this.setState({
        ...this.state,
        isLoaded: true,
        list3Data: response.data.map(location => {
          return { value: location.userId, label: location.title };
        })
      })
    );
  }

  handleChange = ({ target }, name) => {
    if (name === 'selectLocation') {
      this.setState({
        ...this.state,
        selectedlist2DataItem: +target.value
      });
    } else {
      this.setState({
        ...this.state,
        selectedlist3DataItem: +target.value
      });
    }
  };

  render() {
    const { isLoaded } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <>
          <select
            id="selectLocation"
            value={this.state.selectedlist2DataItem}
            onChange={e => this.handleChange(e, 'selectLocation')}
          >
            {this.state.list2Data.map(({ value, label }, index) => (
              <option value={value}>{label}</option>
            ))}
          </select>

          <select
            id="selectLocationn"
            className={
              this.state.selectedlist3DataItem === 1
                ? 'badge-primary'
                : this.state.selectedlist3DataItem === 2
                ? 'badge-secondary'
                : 'badge-danger'
            }
            value={this.state.selectedlist3DataItem}
            onChange={e => this.handleChange(e, 'selectLocationn')}
          >
            {this.state.list3Data.map(({ value, label }, index) => (
              <option value={value}>{label}</option>
            ))}
          </select>

          <table className="table">
            <thead>
              <tr>
                <th>Id</th>
                <th>Name</th>
                <th>Email</th>
              </tr>
            </thead>
            <tbody>
              {this.state.listData &&
                this.state.listData.map(item => {
                  return (
                    <tr key={item.id.toString()}>
                      <td>{item.id}</td>
                      <td>{item.name}</td>
                      <td>{item.email}</td>
                    </tr>
                  );
                })}
            </tbody>
          </table>
        </>
      );
    }
  }
}

Final Output

https://i.stack.imgur.com/YfAZx.png

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

Adding the 'None' option to a select menu using Material UI in a React application can

I am currently working on implementing Material UI React Storybook. To avoid hardcoding select options, I have mapped them out. However, I am struggling to add a "None" option similar to the Material UI select component. When "None" is selected, nothing sh ...

Adjusting the Aspect Ratio of an Embedded YouTube Video

<!DOCTYPE HTML> <head> <style> body { overflow: hidden; margin:0; } </style> </head> <body> <iframe id="video" src="https://www.youtube.com/embed/U4c9bBeUe4M?modestbranding=1&sh ...

Showcasing images stored in Redux state

How can I show an image from a URL stored in my backend? I am trying to display the photo within a card component that is being used for all of my articles, but it's not showing up. Could this be related to the jss file linked to the component? To se ...

Sync State with Data from API Query

I have a scenario where I need to fetch data from two different APIs and update their states separately. Afterward, I am iterating through the NBA data and looping through the animeData object to update the allData state, which will be an array of object ...

Encountering undefined data when trying to access returned JSON data through jQuery Ajax

Utilizing the MVC approach, within my javascript code, I am encountering a discrepancy. Upon using console.log(data.msg) in the success function, the desired result is achieved. However, when attempting to employ $('#res').text("".data.msg), an ...

Steps for updating a specific item within an object in an array of MongoDB document

Consider the following data collection, for which I have some questions: { "_id" : ObjectId("4faaba123412d654fe83hg876"), "user_id" : 123456, "total" : 100, "items" : [ { ...

obtain an inner element within a container using the class name in a div

I am attempting to locate a span element with the class of main-tag within a nested div. However, I want to avoid using querySelector due to multiple elements in the HTML file sharing the same class and my preference against using IDs. I realize there mig ...

Issue with React Router 4.x - PrivateRoute not functioning correctly post integration with Redux

There seems to be an issue with the PrivateRoute from the Example available at https://reacttraining.com/react-router/web/example/auth-workflow. It stops working after being connected with Redux. My version of PrivateRoute is almost identical to the origi ...

Enliven the character limit reaction by incorporating a thrilling shake animation when it reaches

I have implemented a feature in my component where if a user reaches the character limit, the component should shake. However, despite my efforts, the shaking effect is not working in the current code. const useStyles = makeStyles(() => ({ shake ...

Using the CSS property `transform:scale(2,2)` causes an image to suddenly appear in the

Currently utilizing Joomla 3.3, I am seeking to enlarge an image on mouseover. The html code for the image is as follows: <img class="enlarge" style="float: right; margin: 10px; border: 5px solid black;" title="Chapter 1: Physical Differences" src="im ...

Issue with PassportJs not forwarding users after successful authentication

I'm facing some challenges with implementing Passport for authentication. I have set up my signup strategy in the following way: passport.use('local_signup', new localStrategy({ usernameField: 'username', passwordField:&apo ...

Styling targeted div class elements with specific input elements

I have a group of input text elements on my webpage. I am looking to style the div element with the "forms_in_ap" class that contains the #email, #reEmail, #nogInFirstName, and #nogInAccNumber elements specifically for Safari browsers on MAC and IOS device ...

What is the method for ensuring text remains within a square while it is being relocated?

Check out this jsfiddle where you can interact with a moving square: http://jsfiddle.net/helpme128/3kwwo53t/2/ <div ng-app="test" ng-controller="testCtrl"> <div id="container"> <div class="shape" ng-draggable='dragOptions& ...

How can complex POST parameters be structured in a RESTful API?

For my current project, I am working on developing an application utilizing node.js along with express. This application involves a feature that allows users to subscribe to lists of items. Each subscription includes specific options such as minimum scores ...

invoke a managed bean to execute JavaScript code

I am facing an issue while trying to clear a hidden form value in a JSF page from a managed bean class. I tried calling a method where I used the following code snippet to call JavaScript, but unfortunately it throws a java.lang.NullPointerException. The c ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

Jquery refuses to load

Hey everyone! I'm currently working on an HTML file for my Angular 2 course. After setting up the dependencies and downloading them with npm, I encountered an error when trying to run the app... The error message I received was: file:///Users/Rocky/A ...

How can I make a clickable button or link within an anchor tag that is still able to be right-clicked?

Hey there, I'm currently working on a notification dropdown menu where each <li> contains a link or an <a> tag. I'm aiming to create something similar to Facebook's notification system. However, the challenge lies in trying to ...

CSS2DRenderer does not belong to the Three.js library

Before we dive in, let me provide some background information: I recently incorporated three.js into a default React project using npm. Now, I'm interested in integrating this example that utilizes CSS2D. Unfortunately, I encountered an error when a ...

Tips for retrieving the dynamically generated ID within an li tag

I've been diving into the world of JavaScript and jQuery, encountering a few hurdles as I attempt to merge various solutions that I come across. This code represents a mishmash of tutorials I've recently completed. Admittedly, I am quite new to ...