CyberJ
CyberJ

Reputation: 13

Adding variable to JSX string

I'm returning the following HTML in React.

<div 
    className={ props.className } 
    data-slide='{"arrows": true, "slidesToShow": 3, "slidesToScroll": 1}'>
</div>

It returns the following which is ok

<div class="some-class" data-slide="{"arrows": true, "slidesToShow": 3, "slidesToScroll": 1}"></div>

However, I want the value for arrows to be a variable named arrowsVal which I'm setting in my React component.

I tried:

<div 
    className={ props.className } 
    data-slide='{"arrows":' + arrowsVal + ', "slidesToShow": 3, "slidesToScroll": 1}'>
</div>

and

<div 
  className={ props.className } 
  data-slide='{"arrows": `${arrowsVal}`, "slidesToShow": 3, "slidesToScroll": 1}'>
</div>

but it does not work.

Upvotes: 1

Views: 1050

Answers (3)

Rahul kumar
Rahul kumar

Reputation: 44

Try something like:

<div
  className={props.className}
  data-slide={{ arrows: arrowsVal, slidesToShow: 3, slidesToScroll: 1 }}
/>

Upvotes: 0

Allen Wong
Allen Wong

Reputation: 1433

<div 
  className={ props.className } 
  data-slide={{
    arrows: arrowsVal,
    slidesToShow: 3,
    slidesToScroll: 1,
  }}
/>

if you need data-slide to be a string anyway

<div 
  className={ props.className } 
  data-slide={`{"arrows": ${arrowsVal}, "slidesToShow": 3, "slidesToScroll": 1}`}
/>

Upvotes: 0

Mohamed Sadat
Mohamed Sadat

Reputation: 255

This should work i think

<div 
  className={ props.className } 
  data-slide={`{"arrows": ${arrowsVal}, "slidesToShow": 3, "slidesToScroll": 1}`}>
</div>

However the approach that i would recommend is to define a const before return statement of Render method defined as:

const dataSlide = `{"arrows": ${arrowsVal}, "slidesToShow": 3, "slidesToScroll": 1}`

and render it as:

<div 
  className={ props.className } 
  data-slide={dataSlide}>
</div>

I hope this will help :)

Upvotes: 2

Related Questions