Home > OS >  How do I tell if a prop was passed in a react component
How do I tell if a prop was passed in a react component

Time:10-15

I have a react function component, This function takes in some props.

I want to know if the component had a specific prop passed to it.

Say I have a component, Song, that takes in 1 prop, Genre. I would want to know if the component when used was used with the genre prop.

examples:

  • genre not passed:
<Song></Song>
  • genre passed:
<Song genre="Rap"></Song>

edit: clarity

CodePudding user response:

You can just check for the undefined value for the description.

for example:

const MyComponent = ({ title, description }) => {
    return (
        <div class ="card">
            <div class="card-header">{title}</div>
            {description && <div class="card-body">{description}</div>}
        </div>
    )
}

In above example I have used conditional rendering to meet your requirement.

CodePudding user response:

maybe you must create the functional compontent that receive props from parent genre and the default props of genre is all, maybe the component will look like this:

const Song = ({ genre="all" }) => {
   if(genre === "all") {
     return(
        <div>this song list has a all genre</div>
     )
   } else if(genre === "Rap") {
     return(
        <div>this song list has a genre {genre}</div>
     )
   }
}

if we set default props so when from the parent component did not send props genre the default props of genre in song (which is "all") component will be applied.

CodePudding user response:

{props.genre != undefined &&
 <Card.Subtitle>
   {props.genre}
 </Card.Subtitle>
}
  • Related