Changing the background color with a switch function in ReactJS

After clicking a link, a view is rendered based on the "id" from a JSON. To enhance the user experience, I want to add a background color when a particular view renders and also toggle the style.

This code snippet illustrates how the crawl is displayed upon clicking a specific link.

handleCrawl = e => {
  const { id } = e.target;
  this.setState(current => ({
    showCrawl: { [id]: !current.showCrawl[id] }
  }));
};

This is my render method where I map the links along with additional details from JSON.

render() {
  return (

    <div class="d-flex" id="wrapper">

      <div class="bg-light border-right" id="sidebar-wrapper">
        <h1 class="sidebar-heading">API</h1>
        <ul class="list-group list-group-flush">

          {this.state.apis.map(api => (
            <li><a class="list-group-item list-group-item-action bg-light" key={api.id}
              id={api.id}
              onClick={this.handleCrawl}>{api.title}</a></li>
          ))}

        </ul>
      </div>

      <div id="page-content-wrapper">

        <div class="container-fluid">
          {this.state.apis.map(api => (
            <div
              key={api.id}
              id={api.id}>
              {this.state.showCrawl[api.id] && (
                <SwaggerUI url={api.opening_crawl}/>
              )}
            </div>
          ))}
        </div>
        
      </div>

    </div>
    
  );
}

Answer №1

Not certain if this will address your inquiry. You have the ability to change the style based on conditions.

{this.state.apis.map(api => (
    <div
      key={api.id}
      id={api.id}
      className={this.state.showCrawl[api.id]?"some-specific-style":"default-or-empty"}

    >
      {this.state.showCrawl[api.id] && (

        <SwaggerUI url={api.opening_crawl}/>
      )}

    </div>
  ))}           

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

Is it possible to merge several blobs into one zip file using JSzip?

When attempting to download multiple images as a single ZIP file, the result is receiving separate zip files instead. The console log shows that the 'urls[]' array contains different arrays. const fileURLs = window.URL.createObjectURL(result);// ...

Tips for modifying the value of a JSON object using Javascript or Jquery

I am looking to retrieve the value of a specific key, potentially accessing nested values as well. For example, changing the value of "key1" to "value100" or "key11" to "value111. { "key1": "value1", "key2": "value2", ...

The Uglify task in Grunt/NPM is having trouble with this particular line of JavaScript code

Whenever I execute grunt build, Uglify encounters a problem at this point: yz = d3.range(n).map(function() { return k.map(x -> x[1]); }), An error message is displayed: Warning: Uglification failed. Unexpected token: operator (->). I have recentl ...

Using Javascript to parse SOAP responses

Currently, I am working on a Meteor application that requires data consumption from both REST and SOAP APIs. The SOAP service is accessed using the soap package, which functions properly. However, I am facing challenges with the format of the returned data ...

Mobile display exhibiting glitches in animation performance

I have implemented an animation in the provided code snippet. const logo = document.querySelector('.logo'); const buttons = document.querySelectorAll('.loadclass'); const html = document.querySelector('html') const cornerme ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

Unusual spacing issue observed between <div> elements on Internet Explorer, but not on Firefox or Opera

I am facing a common question that many others may have asked before, but I haven't been able to find a solution to my specific issue. When viewing my website on FF, Opera, and IE on Windows 7, everything displays correctly. However, when using IE7 o ...

What causes the issue when attempting to import multiple CSS files in a Vue.js project using @import more than once?

Currently, I am working on a project that involves one main component and several child components. These components require custom CSS files as well as additional vendor CSS files. A challenge I encountered is that I cannot use the @import "path/to/css/fi ...

Issue encountered during ag-grid version upgrade: unable to locate compatible row model for rowModelType 'virtual'

Recently, I updated my ag-grid version from v7.0.2 to v11.0.0, and after the upgrade, all tables with infinite scrolling functionality stopped working abruptly. The browser console displayed the following error message: ag-Grid: count not find matching ...

Bootstrap Popover not displaying information after an AJAX request

I'm struggling to update the popovers contents with Ajax result in my ASP.Net MVC4 project. Using ASP.Net (MVC4): public ActionResult GetEmployeeDetails(string employeeId) { var contract = UnitOfWork.ContractRepository.ContractBu ...

The element type provided is not valid: it should be a string for built-in components or a class/function for composite components. However, an object was received instead. - React Native

After conducting extensive research, I have been unable to find a solution as to why this issue persists. Can anyone shed some light on what the error might be referring to? Error: Element type is invalid: expected a string (for built-in components) or a c ...

Can we utilize object properties in this manner?

Hey there! I've been experimenting with the react-bootstrap library recently, trying to get better at using it. While going through the tutorial, I came across some ES6 code that caught my attention. function FieldGroup({ id, label, help, ...props } ...

What is the best way to display changing data in a React component?

Having some trouble with printing data based on the length of an array. Here is my attempted solution, but unfortunately, it's not working as expected. I believe the issue lies in the cb function within the forEach loop. Below is the code snippet: fun ...

You cannot make a hook call within the body of a function component, unless you are using useNavigate and useEffect in conjunction with axios interceptors

Currently, I am delving into React and attempting to include a Bearer token for private API calls. My approach involves writing a private axios function to intercept requests and responses. Subsequently, I invoke it in my API.js file to fetch data from the ...

Sending an array of objects in JavaScript to a controller

I have a dynamic form that I'm trying to submit to my Controller. Instead of sending just a string or an array with data, I need to pass an array of objects using ajax request after building the Javascript Array. The challenge is that when I send only ...

Explore a variety of images within an array using Gatsby and Markdown documents

After spending more than 6 hours on this, I've decided to call it quits for today. However, I'm hoping someone out there might have a solution. The problem at hand is as follows: I'm trying to include an array of images in a Markdown file t ...

Redirecting with a 301 status code using Google Cloud Endpoint

As I set up a custom domain for my cloud endpoint application, I discovered that this feature does not directly work with the endpoint itself. However, it does function properly for the static HTML page that uses CORS and ReactJS to consume the endpoint se ...

What is the best way to highlight selected navigation links?

Recently, I implemented a fixed navigation bar with relevant links on a website. The navbar includes a jquery script for smooth scrolling when clicked. However, I am struggling to add a selected class to the clicked link. Despite trying various solutions f ...

The AJAX request encountered an error while trying to send a POST request to the http://localhost/upload/undefined endpoint. The

I've been scouring the internet and testing for hours, but I'm still unable to identify the source of the error. I could really use some assistance here. I meticulously followed a tutorial on multiple file uploads with drag & drop functionali ...

Using JavaScript, redirect to a specified URL once a valid password has been entered on an HTML form

Need help with JavaScript for password validation and URL redirection. I'm new to JS and used some resources like Password correct? then redirect & Adding an onclick function to go to url in javascript?. Here's my current code: ...