Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add inline style width:calc(100% / var) in reactjs?

Tags:

html

reactjs

 for (let i = 0; i < divCount.length; i++) {
        var radio = divCount[i].getElementsByClassName("radio_count");
        for (var index = 0; index < radio.length; index++) {
            var element: any = radio[index];
            console.log(element);
             var style ="width:calc(100% / " + element + ")";
            element.style = style;
        }

    }
  1. i want add inline style
  2. set dynamic value in 100% divided ex. width:clac(100% / var); how can i do this ?
like image 897
Dhrupal Suthar Avatar asked Jun 22 '17 07:06

Dhrupal Suthar


People also ask

Can you use Calc in inline styles?

Using the calc() function in inline styles in React # Set the style prop on the element. Pass the result of calling calc() as the value for a CSS property. The call to calc() should be wrapped in a string, e.g. 'calc(100% - 600px)' .

What is inline width?

The width of an inline element is the width of the content. The height and width of an inline element cannot be set in CSS. You cannot set the height and width of block-level elements in CSS.


2 Answers

Template literals should help.

<div style={{width: `calc(100% / ${yourVariable})`}}></div>

Example https://jsfiddle.net/69z2wepo/81579/

like image 86
Andrew Avatar answered Sep 21 '22 21:09

Andrew


What @Andrew wrote is correct, however here's a non ES2015/ES6 version (the question did not specify):

In the react component render, you can use the following JSX:

render: function() {
    var dynamicWidth = 'calc(100% / ' + value + ')';
    return (
      <div>
        <div style={{width: dynamicWidth}}></div>
      </div>
    );

Basically how this works is on each render that string gets interpolated. What @Andrew has shown you is just a better syntax available to do the same thing in ES6

calc(100% / ${value}) is conceptually equivalent to 'calc(100% / ' + value + ')'

like image 31
bakkal Avatar answered Sep 22 '22 21:09

bakkal