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

Creating Redux reducers dynamically

I'm feeling a bit puzzled about how to dynamically generate reducers in Redux. I've come across some Stackoverflow threads discussing this topic, but they seem to address various scenarios and leave me somewhat confused with the proposed solutio ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

Issues with Async Ajax functionality are being reported specifically in Safari browsers when a redirect

Encountering issues with an async Ajax call not functioning in Safari while working perfectly fine in other browsers. The problem arises when there is a redirect/link on the button or anchor that triggers the Ajax function. Here's a basic example: & ...

Customizing checkboxes in React with JSS: A step-by-step guide

I'm currently working on customizing CSS using JSS as my styling solution, which is proving to be a bit complex while following the w3schools tutorial. https://www.w3schools.com/howto/howto_css_custom_checkbox.asp HTML: <label class="container"& ...

Reference now inactive in an array object no longer exhibiting reactivity

After implementing the following code successfully, we noticed that changing the language updates the text correctly thanks to the ref: const mainNavigationLinks = computed(() => [ { label: context.root.$t('navigationMenu.home') }, { labe ...

Unusual behavior in sorting values with JavaScript

I have spent hours trying to figure this out, and the only conclusion I can come to is that when there are 14 elements to sort, it doesn't function properly, but with thirteen elements, it works perfectly. My goal is to sort DIV elements based on the ...

Utilize Windows Phone to Encode NFC Tag

I am currently working on writing and reading NFC tags using the ProximityDevice class on Windows Phone 8.1. Here is the code snippet I'm using to write the tag... var dataWriter = new Windows.Storage.Streams.DataWriter(); dataWriter.unicodeEncoding ...

Issues encountered while trying to open and close a div using jQuery

.box-one { border: 0.1em solid #ccc; } .dropdown-info { display: none; } <div class="box-one"> <div class="header"> <h3 class="text-center">Sample Header</h3> </div> <div class="dropdown-info"> <p ...

Troubleshooting problems with hosting create-react-app on IIS and Internet Explorer

Having some trouble setting up my React application that was built using the React Create App template. When trying to host it with IIS, I encountered some issues. The index.html main page seems to be loading fine, but the compiled JS file is not loading ...

Tips for activating an HTML input field using Javascript

I am currently using localStorage to store a string input by the user as a title, which will be saved for future visits. I would like to implement a button that allows the user to delete the displayed text (from localstorage) and enables the input field fo ...

How to reset the source and layer when updating map styles with the react map gl library

I'm having trouble switching the map view from streets to satellite using components from the React Map GL library. When I try to change the style, the compiler can't find the corresponding layers' sources and throws errors in the console. T ...

When the Image Icon is clicked, the icon itself should become clickable and trigger the opening of a popup Dialogue Box for uploading a new image

When I click on the image icon, it should be clickable and a popup dialogue box will open to upload a new image. Check out this sample image for reference. Any help on this would be greatly appreciated. Thanks in advance. <div class="d-flex align-ite ...

Exploring Protractor testing with Bootstrap modals

I'm having an issue testing a bootstrap modal. Here's the scenario: Click on a button to display the modal The modal body has a list of buttons When I click on one of them, it doesn't do anything My Protractor code snippet: element(by. ...

The JavaScript jump function quickly moves back to the top of the webpage

Issue Resolved To prevent the view from jumping to the top of the page, I have implemented three options: Set the href attribute to href="#!" Set the href attribute to href="javascript:;" Pass the object to the event-handler and preve ...

Angular input range slider that automatically rounds decimal values from the data bindings

I've implemented a range slider within an Angular form to capture and display recorded values. <input [formControlName]="object.id" [id]="object.id" type="range" [(ngModel)]="object.answer" [step]="objec ...

What is the best way to position the "initial" async action in React/Redux for optimal performance?

Having experience with multiple React/Redux projects, I frequently encounter components that require initialization with server data through asynchronous calls. I typically utilize componentDidMount to trigger a Redux action for populating the initial da ...

Curved edges, Layering, Content overflow restriction

My design consists of two circular divs with the border-radius property set to its max value. The first circle contains a header div with a unique background-color and overflow:hidden to create the illusion that the top portion of the circle has a differen ...

What is the best way to showcase a local image in the console using nwjs?

I am currently developing a desktop application using NW.js (node-webkit). In relation to this topic google chrome console, print image, I am attempting to display an image in the console. Following the suggestion from the aforementioned topic, the follo ...

Utilizing Weather APIs to fetch JSON data

Trying to integrate with the Open Weather API: Check out this snippet of javascript code: $(document).ready(function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $(".ok").html("latitude: " + ...

I can't seem to get the dropdown list to appear. What could be the issue?

I'm currently trying to create a pure CSS dropdown menu on hover by following this tutorial. However, despite multiple attempts, I'm still stuck and in need of some clear explanations for my issue. <div class="navbar"> ...