Issue with React JS if statement behaving erroneously within HTML code

I'm a beginner in React and I'm attempting to create a dynamic data display box.

const Widget = ({type}) => {
let data = {
    title: "",
    increase: false,
    amount: 0,
    link: "View Billing",
    icon: <KeyboardArrowUpIcon classname={"icon"}/>
};

To handle the different types that are received, I used a switch case.

switch (type){
    case "Billing":
        data={
            title: "Billing",
            increase: false,
            amount: 4000,
            link: "View Billing",
            icon: <MonetizationOnOutlinedIcon className="icon"/>
        };
        break;

In order to display an icon based on the 'increase' value, I set up the if clause like this.

return(
  <div className="widget">
      <div className="left">
          <span className="title">{data.title}</span>
          <span className="counter">{data.amount}</span>
          <span className="link">{data.link}</span>
      </div>
      <div className="right">
          <div className="percentage positive">

              {(data.increase)? <KeyboardArrowUpIcon/> + ["20"] : <KeyboardArrowDownIcon/> + ["-13"]}
          </div>
          {data.icon}
      </div>
  </div>

)

But the output I'm seeing is

https://i.sstatic.net/fWFzp.png

Somehow, for reasons unknown to me, the icon is not being displayed by this clause.

                  {(data.increase)? <KeyboardArrowUpIcon/> + ["20"] : <KeyboardArrowDownIcon/> + ["-13"]}

What am I missing? I attempted using an if statement within the div but couldn't get it to work. This method sort of works, but it fails to render the icon correctly.

Answer №1

Consider trying out this solution

return(
  <div className="widget">
      <div className="left">
          <span className="title">{data.title}</span>
          <span className="counter">{data.amount}</span>
          <span className="link">{data.link}</span>
      </div>
      <div className="right">
          <div className="percentage positive">

              {
                data.increase? 
                  <>
                    <KeyboardArrowUpIcon/> 20
                  </> : 
                  <>
                    <KeyboardArrowDownIcon/> -13
                  </>
              }
          </div>
          {data.icon}
      </div>
  </div>
);

The issue here lies in trying to combine the component instance with an array, resulting in the display of 'Object object'

Answer №2

This equation doesn't seem to add up:

<KeyboardArrowUpIcon/> + ["20"]

Attempting to combine a component with an array doesn't have any logical meaning. The end result is simply the engine converting them to strings and putting them together.

If your intention is to just display the component and the string "20", then you can directly output them as such. In JSX syntax, you would encapsulate them within a containing element:

<><KeyboardArrowUpIcon/>20</>

To make it clearer, you can add spaces like this:

<>
  <KeyboardArrowUpIcon/>
  20
</>

Answer №3

Every React node must be contained within a single container. Make sure to enclose your logic in a div or React.Fragment (abbreviated as <></>).

{(data.increase) ? 
(<>
<KeyboardArrowUpIcon/> + ["20"]
</>) 
: (<>
<KeyboardArrowDownIcon/> + ["-13"]
</>)}

I am curious why you are using square brackets for the numbers 20 and -13. Without knowing the specifics of your app's logic, I suspect your code may look more like this.

{(data.increase) ? 
(<>
<KeyboardArrowUpIcon/>
<div>20</div>
</>) 
: (<>
<KeyboardArrowDownIcon/>
<div>-13</div>
</>)}

Hopefully, this provides the clarity you were seeking.

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

Incorporating Google's Document AI API into a ReactJs application

Has anyone successfully integrated the Cloud Document AI API with ReactJs? If so, can you share the integration process? Here is the documentation for reference I haven't been able to find a clear method for integrating it into ReactJs. ...

Adjust handle on HTML input element similar to textarea element

Is there a way to enable a resize handle on input elements similar to the one present on textarea elements by default (the little area at the bottom right corner that allows you to click and drag to resize the textarea box)? I attempted to add 'resiz ...

I am looking to switch the input border-bottom color to blue when the input field is focused or has valid content

Can someone help me change the border bottom color of my input to blue in the following HTML code: .inputBox input:focus ~ input, .inputBox input:valid ~ input{ border-bottom: 1px solid #0000cd; } <div class="i ...

Modifying SAS ODS contentitem in PROC SQL SELECT query

When using SAS to generate ODS output in HTML format, you have the option to include a table of contents with the "CONTENTS" and "FRAME" settings: ODS HTML PATH="C:\Path\" (url=none) BODY="body.html" CONTENTS="contents.html" ...

What are the ways to implement global functions in Vue.js?

I have a function that formats dates without time. I want to reuse this function in multiple components. What is the recommended approach for handling this scenario? Should I use directives, filters, or another method? How should I go about defining this ...

Unable to clone curved text in fabric.js version 5.3.0

I am currently using fabric.js version 5.3.0 and I have a requirement to clone curved text and add it to the canvas. Description: The issue I am facing is that the cloning functionality does not work properly with curved text. The cloned object does not r ...

Determining the value of an object property by referencing another property

Upon running the code below, I encounter the following error message: Uncaught TypeError: Cannot read property 'theTests' of undefined $(document).ready(function() { var Example = {}; Example = { settings: { theTests: $(&apo ...

Align the Bootstrap button with the submit button inside a table cell

I am currently utilizing Bootstrap in my Symfony application, and within the index action, I have a table displaying all items along with two buttons for updating or deleting an item. Instead of using two separate buttons, I have opted to use one button to ...

CoffeeScript and Node.js: Encountering an Unexpected ">" Token (Arrow Function)

After attempting to execute the following coffeescript, the issue arises: request = require('request') request('http://google.com', (error, response, body) -> if not error and response.statusCode is 200 console.log(body ...

Maintain the fixed position of the Google Map <div> while allowing background <div>s to scroll

I'm having trouble keeping a Google Map div fixed on the screen while allowing my background, consisting of multiple scrolling divs with content inside, to scroll as normal. My attempt to wrap the map div in another fixed div resulted in the map disa ...

How can I use a for loop to selectively exclude specific elements in JSON objects within an array?

My goal is to execute the function checkIsObjectEmptyOrNot only when the fields "name", "age", and "class" do not contain null values. In case all these values are null (excluding id and book_id), the function should return false. The filtering process mus ...

What is the best way to position one div above another div?

I'm struggling to move the div containing the product name, amount, price, and total to the top of its parent div. Changing the position and vertical alignment properties have not been effective. I've attached a screenshot of the page where the b ...

Issue with StyleX defineVars not being applied in Next.js project (turboRepo)

I am currently working on a Next.js project with turboRepo and using StyleX for styling. I have run into an issue where the design tokens defined with stylex.defineVars are not being applied as expected. Here's a breakdown of my project structure and ...

Creating a factory in AngularJS to handle RESTful JSON communication with

I have a scenario where I need to call a factory from multiple controllers in order to fetch JSON data. When I tried calling the factory directly from the controller, it worked successfully. However, after adding a factory and checking the console for erro ...

Regular expression ignores the initial "less than" character

Question Statement: From: John Doe <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb7b2b5b3aeb0b4a9b59dbab0bcb4b1f3beb2b0">[email protected]</a>> Date: Mon, 25 Oct 2021 09:30:15 -0400 Message-ID: << ...

The state change in NextJS button becomes visible after the second click

An avid learner exploring Next.js. I am eager to create a component that displays the window width and height along with a Tailwind CSS breakpoint when a button is clicked, as a first step towards continuous display. I chose to implement a button click ev ...

Modifying HTML tag attributes with inline server scripts

I am working with a submit button and trying to change the background color of the button itself after it has been clicked using inline server tags. <form id="form1" runat="server"> <input type="submit" id="submit" value="Submit" runat="server"/& ...

Utilizing Bootstrap's Multi-Grid System

I am currently working on implementing a Bootstrap grid design that resembles pic1.jpg. However, I am facing challenges in achieving the desired layout, as pic2.jpg shows the current scenario. Below, I have shared the code I am using. pic1.jpg :- ! pic2. ...

Navigating paths post form submission

Greetings esteemed teachers of StackOverflow. I am following Ben Awad's fullstack tutorial and attempting to implement an image upload feature for creating posts. It seems like everything is functioning correctly, as the posts (including images) are b ...

Trimming content within an editable div in JavaScript: A guide

I am working on an editable div feature where users can input text for comments. My goal is to eliminate any unnecessary spaces before and after the text. For example, if a user types: "&nbsp;&nbsp;Hello&nbsp;world&nbsp;&nbsp;&nbsp ...