Reputation: 1042
Hi i have issue to use calc in my render function in react.
render() {
let top =0;
let left =0;
if(this.props.top !==undefined){
top=this.props.top;
}
if(this.props.left !==undefined){
left=this.props.left;
}
let topval = `calc(50% + ${top})`, leftval = `calc(50% + ${left })`;
console.log(topval);
console.log(leftval);
return (
<div className={"d-flex flex-column justify-content-center text-center position-absolute loading-animation"}
style={{top:topval,left:leftval,transform:("translate(-50%,-50%)")}}>
<div>
<Spinner animation="grow" variant="success" />
<Spinner animation="grow" variant="danger" />
<Spinner animation="grow" variant="warning" />
</div>
<span>{this.props.loadingMessage}</span>
</div>
);
This is what i am trying to do. If i get props top or left i need to plus that value to 50% from top and left. My example above not work and it just ignoring top and left attributes in my style.
Upvotes: 1
Views: 3899
Reputation: 14413
First, you need to remove the ()
brackets from the properties. Then you can calculate them outside the return
:
render(){
// Assuming values are in pixels
let topval = `calc(50% + ${top}px)`, leftval = `calc(50% + ${left}px)`;
// rest of the code
return(
<div
style={{top: topval, left: leftval, transform: "translate(-50%,-50%)"}}
/>
)
}
Also make sure to add units like px
, em
etc. when dealing with non-zero values otherwise the css is invalid.
For eg. calc(50% - 10)
is wrong, calc(50% - 10px)
works
Upvotes: 2
Reputation: 51
You can use Template Strings to resolve this
style={{ top: `calc(50% + ${top})`, left: `calc(50% + ${left})` }}
Upvotes: 0