Search code examples
javascriptjsonreactjsshow-hide

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


I'm trying to hide or show an HTML element based on the existence of a JSON key in the data I'm bringing in. If the key exists, I'd like to show the element ID I'm putting that object in. If the key doesn't exist, I'd like to hide the same element ID. I'm using React and not sure if this belongs in the componentDidMount or a regular function. I'm a newbie, so my apologies if I accidentally leave out important code or am writing crappy stuff.

My componentDidMount code:

componentDidMount = () => {
  // Need to hide an the HTML element if the json key doesn't exist in the object
  //check the JSON object for the key "workExamples"
  if (typeof props.workItemData.workExamples === "undefined") {
    console.log("it did not find the json key");
    // Change element styling to hidden
    document.getElementById("work-examples").style.visibility = "hidden";
  } else {
    return;
  }
};

My HTML:

<span id="work-examples" className="work-examples">
  <a href={props.workItemData.workExamples}>Work Examples</a>
</span>

I'm assuming I don't need to post my JSON objects. I have several; only one has the workExamples key. I'm using .map() to list the objects.

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.


Solution

  • As Luke notes in the comments,

    the logic for whether or not to render should live in render

    Mechanics of this have since been covered by other answers here, so I won't go through it all.

    A few other points:

    You're trying to use an arrow function to define the standard React function componentDidMount, and based on a quick local test, I don't think React can understand that. It doesn't look like you're getting any particular benefit from it over the traditional componentDidMount() { /* do stuff here */ } syntax, so I'd switch to the latter.

    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>
    

    is attempting to set the value of href with a value from JavaScript (the stuff in the curly braces). That's valid for JSX, which makes sense since you're using React, but not in pure HTML. But since the page is loading and just not handling a certain part of the logic correctly, I'm assuming you just meant the HTML-like stuff inside your JSX (a something.js file) and not literally an HTML file.