1

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.

1
  • You'll probably get a few different answers to this, but in general, when I need to perform logic/processing within JSX, I try to do it in a separate function that I call within the brackets. so, data-slide={createDataSlideString()}, and then before your render's return(), function createDataSlideString(){...code that creates your string}. This makes it easier to avoid JSX character-escape issues in your expressions. Commented Sep 19, 2018 at 14:08

3 Answers 3

2

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Is there any particular reason for defining a const first? Rather than just adding it to return.
It's juste more helpful for readability because it offers less code in your return statement.
0
<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}`}
/>

Comments

0

Try something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.