How to hide an the HTML element if a JSON key doesn't exist in React

Asked
Active3 hr before
Viewed126 times

9 Answers

elementreact
90%

In React I wanted to display only existing elements after mapping, so in the list element I added CSS logic: ,With the above code, it's not hiding the elements in the list for the JSON objects that don't have the key. Hopefully this all makes sense. Any assistance is appreciated., Is it possible for everything that exists to have a definition?

You're trying to check on whether your JSON contains the key with

typeof props.workItemData.workExamples === "undefined"

but I don't see a need for the typeof; you can just check for the presence of the key directly:

if (props.workItemData.workExamples) {
   /* do stuff */ }

Finally, in your HTML, the line

<a href={props.workItemData.workExamples}>Work Examples</a>
load more v
88%

Without if statements in JSX, how do you control your application's flow? Let's explore how to render or NOT render elements in React.,You can't embed if statements in JSX. So how do you control what is displayed? Controlling flow through your application is fundamental to programming, and it's no different in React. In this article, we are going to answer the question: How do I show or hide something in React?,When you need to control whether one element vs. another is displayed, or even one element vs. nothing at all (null), you can use the ternary operator embedded inside of a larger portion of JSX.

Because this if statement is not embedded inside of JSX but is just part of the regular JavaScript portion of the function, you are free to use any sort of JS construct that you like. In this example, if the product is not available, we're just going to return null.

const AddToCart = ({ available }) => {
  if (!available) return null;

  return (
    <div className="full tr">
      <button className="product--cart-button">Add to Cart</button>
    </div>
  );
};
load more v
72%

prop: This parameter is required. It specifies the string name or Symbol of the property to check.,Return value:It return a boolean denoting if the object has the specified property as own property.,Example 1: This example checks for prop_1 of the obj by using hasOwnProperty property.

obj.hasOwnProperty(prop)
load more v
65%

The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.,React does not yet recognize the attribute you specified. This will likely be fixed in a future version of React. However, React currently strips all unknown attributes, so specifying them in your React app will not cause them to be rendered.,You are using a non-standard DOM attribute on a native DOM node, perhaps to represent custom data. If you are trying to attach custom data to a standard DOM element, consider using a custom data attribute as described on MDN.

function MyDiv(props) {
  if (props.layout === 'horizontal') {
    // BAD! Because you know for sure "layout" is not a prop that <div> understands.
    return <div {...props} style={getHorizontalStyle()} />
  } else {
    // BAD! Because you know for sure "layout" is not a prop that <div> understands.
    return <div {...props} style={getVerticalStyle()} />
  }
}
load more v
75%

Here comes the most tricky part of the JSON name-value pair rendering. React does not directly allow us to render any object in JSX. If we mistakenly do that, it will result in the following error:,And now, the last part of the guide, but of course not the least. Rendering array values in UI with proper styling is one of the common things we do in applications such as Todo App, Travel App, etc.,I hope this guide was helpful in understanding the basics of JSON, React, JSX, and how to render different types of values efficiently to create meaningful user interfaces.

1 {
   2 "string": "Pluralsight",
      3 "number": 1,
      4 "true": true,
      5 "false": false,
      6 "null": null,
      7 "arrayOfStrings": ["a", "b", "c", "d"],
      8 "arrayOfNumbers": [1, 2, 3, 4, 5],
      9 "arrayOfBooleans": [true, false, true, false],
      10 "arrayOfObjects": [{
         "a": 1
      }, {
         "a": 2
      }],
      11 "object": {
         12 "anyKey": "anyValue"
         13
      }
   14
}
load more v
40%

So in this post, we’ll break down how you can make dynamic forms in React, including how to do conditional control over fields appearing and page navigation.,Copyright © Aaron Powell 2021.,Now our full form is looking like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
load more v
22%

Convert the form’s child elements to JSON.,Use built-in browser APIs to get form values as JSON. Zero dependencies and only a few lines of code!,Check to make sure only form field elements are added to the object.

Pretag
 Pretag team - issue, fix, solve, resolve
60%

If json["dir"] doesn't exist or if json["dir"] is not a string, return. ,1.1.2 Using a link element to link to a manifest , § 1.1.2 Using a link element to link to a manifest

{
   "lang": "en",
   "dir": "ltr",
   "name": "Super Racer 3000",
   "short_name": "Racer3K",
   "icons": [{
      "src": "icon/lowres.webp",
      "sizes": "64x64",
      "type": "image/webp"
   }, {
      "src": "icon/lowres.png",
      "sizes": "64x64"
   }, {
      "src": "icon/hd_hi",
      "sizes": "128x128"
   }],
   "scope": "/",
   "start_url": "/start.html",
   "display": "fullscreen",
   "orientation": "landscape",
   "theme_color": "aliceblue",
   "background_color": "red"
}
load more v
48%

Another key piece of a Spring Data REST application is a corresponding repository definition, as follows:,When fetching an individual resource (not a collection resource), Spring Data REST automatically adds an ETag response header with the value of this field.,With this configuration, you can now tap into Spring Data REST events and publish them over a WebSocket.

@Entity(1)
public class Employee {

   private @Id @GeneratedValue Long id;
   (2)
   private String firstName;
   private String lastName;
   private String description;

   private Employee() {}

   public Employee(String firstName, String lastName, String description) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.description = description;
   }

   @Override
   public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;
      Employee employee = (Employee) o;
      return Objects.equals(id, employee.id) &&
         Objects.equals(firstName, employee.firstName) &&
         Objects.equals(lastName, employee.lastName) &&
         Objects.equals(description, employee.description);
   }

   @Override
   public int hashCode() {

      return Objects.hash(id, firstName, lastName, description);
   }

   public Long getId() {
      return id;
   }

   public void setId(Long id) {
      this.id = id;
   }

   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }

   public String getDescription() {
      return description;
   }

   public void setDescription(String description) {
      this.description = description;
   }

   @Override
   public String toString() {
      return "Employee{" +
         "id=" + id +
         ", firstName='" + firstName + '\'' +
         ", lastName='" + lastName + '\'' +
         ", description='" + description + '\'' +
         '}';
   }
}
load more v

Other "element-react" queries related to "How to hide an the HTML element if a JSON key doesn't exist in React"