admin管理员组

文章数量:1390728

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 ponentDidMount or a regular function. I'm a newbie, so my apologies if I accidentally leave out important code or am writing crappy stuff.

My ponentDidMount code:

ponentDidMount = () => {
  // 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.

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 ponentDidMount or a regular function. I'm a newbie, so my apologies if I accidentally leave out important code or am writing crappy stuff.

My ponentDidMount code:

ponentDidMount = () => {
  // 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.

Share Improve this question asked May 7, 2018 at 20:19 Kelly NelsonKelly Nelson 477 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 2

As Luke notes in the ments,

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 ponentDidMount, 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 ponentDidMount() { /* 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.

The code you posted doesn't really make any sense. You should read up on React and how it works. You wouldn't ever need to DOM-select-by-ID an HTML element being rendered by a React ponent from within that React ponent. Instead, you simply have the React ponent's render function check your conditional and then render the HTML accordingly.

Except that actually here, you don't even to do that, because if you're using map the way that I think you are (you didn't post your data so it's hard to tell), then you can just generate an HTML element for each item in the array. So if it's not in the array, it won't map().

render() {
    let workItems = this.props.workItemData ? this.props.workItemData.map((item) =>
        <span id={Object.keys(item)[0]} className={Object.keys(item)[0]}>
            <a href={item[Object.keys(item)[0]]}>{Object.keys(item)[0]}</a>
        </span>
    ) : '';

    return (
        <div>
         {workItems}
        </div>
    );

Try this

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

If you are just taking the prop and potentially outputting it, you could keep it simple and just name what you need in a variable.

render() {
  let conditionalElement = null;
  if(props.workItemData.workExamples) {
    conditionalElement = (
      <span id="work-examples" className="work-examples">
        <a href={props.workItemData.workExamples}>Work Examples</a>
      </span>
    );
  }
  return (
    <div>
      {conditionalElement}
    </div>
  );
}

This will allow you to have a null value which can be injected into JSX if need be (won't produce anything), then check if the prop is there, and then replace the null value with your JSX.

Also, yes, go with the standard ponentDidMount() {} function syntax and typeof would have been unnecessary.

I would remove objects without the key before any of their corresponding ponents have been created. Something like:

render() {
  return (
    <div>
      {
        Object.keys(workItems)
        .filter(item => item.workExamples)
        .map(item => <YourComponent {...item} />)
      }
    </div>
  )
}

In React I wanted to display only existing elements after mapping, so in the list element I added CSS logic:

 render() {
  return (
    <div>
      {
        data.map ((item) => {
        return (<div>

    <li>{item.answer1}</li>
    <li>{item.answer2}</li>
    <li>{item.answer3}</li>
    <li style = {{display: item.answer4 ? 'block' : 'none'}}> 
     {item.answer4}</li>
    <li style = {{display: item.answer5 ? 'block' : 'none'}}> 
     {item.answer5}</li>
    <li style = {{display: item.answer6 ? 'block' : 'none'}}> 
      {item.answer6}</li>

) ) } ) }

本文标签: javascriptHow to hide an the HTML element if a JSON key doesn39t exist in ReactStack Overflow