I know how to use different class in jsx using if else short hand in jxs, but how can I do that too with style?
says I have a loop where I need to check whether a property is present, if yes add margin top 10 to a div?
<div style={{marginTop:10}} />
if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.
Conditional Styling with Inline Styles Add the following code to your App. js: import { React, useState } from "react"; import "./App. css" function App() { const styles = { popup:{ display:"none", opacity:"0" } }; return ( <div className="main"> <button className="open_button">Open!
You cannot use if-else statements inside JSX. If you want to check conditions inside JSX, use the ternary operator or put the conditional logic into a function and call that function from JSX. React follows a declarative programming style. React compiles regular JSX expressions to regular JavaScript function calls.
With inline if-else:
<div style={isMarginNeeded ? {marginTop:10} : {}} />
You can read more about it here
You can do it like this:
<div style={present ? {marginTop:10} : {}} />
or like this:
<div style={{marginTop: present ? 10 : 0 }} />
or more complicated style with spread operator:
<div style={{
marginLeft:10,
...( present ? {marginTop:10} : {} ),
}} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With