Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react jsx inline if else altering style value

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}} /> 
like image 424
Giala Jefferson Avatar asked May 26 '17 09:05

Giala Jefferson


People also ask

Can we use if-else in JSX?

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

How do you conditionally add styles in React?

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!

How do you write if-else statements in JSX?

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.


2 Answers

With inline if-else:

<div style={isMarginNeeded ? {marginTop:10} : {}} /> 

You can read more about it here

like image 88
OurOwnOwl Avatar answered Oct 08 '22 14:10

OurOwnOwl


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} : {} ),
}} /> 
like image 33
oklas Avatar answered Oct 08 '22 16:10

oklas