简体   繁体   中英

How to conditional render css inline

Basically, I can do this because, I conditional render backgroundColor, but I want also render a position. I want some data was display on right, other on left. My problem is I have no idea why any of css I used not work: align, alignText, position work halfy float but it cause other thing was destroyed in half.

      {Data.map(i => (
        <StickyContainer
          key={i.id}
          className="container"
        
          style={{  alignText: "right", backgroundImage: `url("/zalety/${i.id}.jpg")`, 
        backgroundSize: "cover", 
    }}
        >
          <Sticky>
            {({ style }) => (
              <h1 style={{ ...style, background:   "#ae4a84", textAlign: "center" }} > {i.title} </h1>
            )}
          </Sticky>

          <h2 className="text-center" style={{width: "45%", backgroundColor:  (i.color ) ? `${i.color} ` : "white",
     
        
        }}>{i.content}</h2>
          
        </StickyContainer>

I tried to use a component such as ExampleCard or something and there put this but it caused error with class/functional component.

To conditionally add the inline css, since this is a JS Object that you're passing in to the style props, you can construct the object along with JS spread operator like below:

 ... <h2 className="text-center" style={{width: "45%", backgroundColor: (i.color )? `${i.color} `: "white",...(<condition for right alignment>)?{<CSS props for right alignment>}:{}}>{i.content}</h2>...

Replace the each <> with the appropriate data. The above change will make it so that you only apply the CSS when the condition is true.

For styling and position to the right or left, I usually do something like {position:'absolute', right: 0} but this will only work if your StickyContainer , or whatever the direct parent of your h2 , has a position of relative , otherwise, it will adjust itself with the most recent parent that have the position of relative .

To future generation, after traing all methods to transform it, just I had a golden shot:

transform: (i.position == 'right') ? "translate(100%, 0)" : null,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM