How do I check if the object has a specific name string in Reactjs?

Asked

Viewed 36 times

-1

I want to render an image only if my object has the "happy" property, so play the image I want only if this is the string. My object is an API Example:

api = {
 type: "happy"
}
someFunction(){
  return({api.type[0] === "happy"? (<img src={happy.png} />) : (<img src{sad.png}/>)"})
}
  • Property (key) or value "happy"? What you implied in your question was whether an object has something like { happy: "algum valor..." }.

2 answers

0

How are you already getting the attribute type directly from your object api just you in your job

someFunction(){
  return({api.type === "happy"? (<img src={happy.png} />) : (<img src{sad.png}/>)"})
}

Since you have only one object of type api and its attribute type is no object array has no need for you to access the type[0]

0


Try not to use loose values for comparisons of this type, store in a constant. It is also important to consider how the data flow between the components is, prioritize the Hoc (Higher-Order Component).

const TYPE_HAPPY = "happy";

const ImageHappyOrSad = ({ type }) =>
  type === TYPE_HAPPY ? <img src={happy.png} /> : <img src={sad.png} />;

const App = () => {
  const api = {
    type: "happy",
  };

  return <ImageHappyOrSad type={api.type} />;
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.