Reputation: 4022
I am scratching my head with this one (should be so easy) but I'm struggling to work out how to conditionally render a data attribute based on props being passed down.
Here is the code snippet WITHOUT the extra data attribute but showing a working ternary operator
<ul
data-slider
ref={carouselEL}
className={props.trending ? "flex lg:grid lg:grid-3" : "flex transition lg:w-full"}
>
Here is an example with the additional data attribute, yet the bottom line of code throws an error and doesn't work.
<ul
data-slider
ref={carouselEL}
className={props.trending ? "flex lg:grid lg:grid-3" : "flex transition lg:w-full"}
{props.trending && dataTrending}
>
Any ideas?
To confirm the desired output for a carousel WITH data trending true should be
<ul
data-slider
class="flex lg:grid lg:grid-3"
data-trending
>
Thanks, Adrian
Upvotes: 0
Views: 1804
Reputation: 53944
In JSX
, properties must be key-value
pairs,
that's why such code is a SyntaxError
:
<ul
{props.trending && dataTrending}
/>
----
SyntaxError: Unexpected token, expected "..." (2:3)
1 | <ul
> 2 | {props.trending && dataTrending}
| ^
3 | />
Here are some use cases to handle component properties:
const divStyle = {
style: { width: 200, padding: 5, border: '1px solid black' }
};
const conditionalProps = isTrue ? divStyle : null;
<>
<div {...divStyle}>Toggle Props</div>
<div style={value ? { ...divStyle.style } : null}>Toggle Props</div>
<div {...conditionalProps}>Toggle Props</div>
</>
In your case:
<ul
dataSlider
ref={carouselEL}
className={props.trending ? "flex lg:grid lg:grid-3" : "flex transition lg:w-full"}
dataTrending={props.trending ? {...dataTrending} : null}
// May cause a bug due to short circuit.
// dataTrending={props.trending && dataTrending}
/>
// Or
const dataTrendingProp = props.trending ? dataTrending : null;
<ul
dataSlider
ref={carouselEL}
className={props.trending ? "flex lg:grid lg:grid-3" : "flex transition lg:w-full"}
{...dataTrendingProp}
/>
Note: In JSX, attributes should be
camelCased
, i.edataSlider
ant notdata-slider
"In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attribute tabindex corresponds to the attribute tabIndex in React."
Upvotes: 0
Reputation: 629
This should do the trick if you want just the data attribute without any value:
<ul data-trending={props.trending ? '' : null} >
Upvotes: 1
Reputation: 34
In order to use the unordered list (<ul>
element) You have to generate list item (<li>
element) for each entry, like so:
<ul
data-slider
ref={carouselEL}
className={props.trending ? "flex lg:grid lg:grid-3" : "flex transition lg:w-full"}
>
{props.trending ? dataTrending.map((item, index) => <li key={index}>{item}</li> : null}
</ul>
<ul>
element we're passing the key
propArray.prototype.map
the first argument is the item and the second one is the item index in the array, read more here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/mapUpvotes: 0