Last updated: Apr 7, 2024
Reading time·2 min
To use the calc()
function in React:
style
prop on the elementcalc()
as the value for a CSS property.calc()
should be wrapped in a string.const App = () => { const navbarHeight = '200px'; const footerHeight = '100px'; return ( <div style={{ minHeight: `calc(100vh - ${navbarHeight} - ${footerHeight})`, }} > <h2>Hello world</h2> <div style={{width: 'calc(100% - 600px)'}}> <h2>Some content here</h2> </div> </div> ); }; export default App;
We set the style
prop on the div
in order to use
inline styles.
The first example uses a template literal to interpolate variables in the call to the calc() function.
<div style={{ minHeight: `calc(100vh - ${navbarHeight} - ${footerHeight})`, }} > ... </div>
The expressions in the dollar sign curly braces ${}
syntax will get replaced
with the actual values of the navbarHeight
and footerHeight
variables.
Note that template literals are wrapped in backticks ``, not single quotes.
The second example uses the calc()
function to calculate the width of an
element.
<div style={{width: 'calc(100% - 600px)'}}> <h2>Some content here</h2> </div>
Note that the minus (or plus) sign has to have spaces on both sides.
The call to the calc()
function has to be wrapped in a string.
I've also written an article on how to use !important with inline styles in React.
You can learn more about the related topics by checking out the following tutorials: