AoXNeR
AoXNeR

Reputation: 77

React adding conditional styling (&&)

the same newbie here. I have the code which working as intended, all I want to do is add && with state variable (boolean) to make a text have line-through decoration while clicked (using crossedItemOnClick)

import React, { useState } from 'react';
import ReactDOM from 'react-dom';

function Para(props) {
    const {id, className, info, state} = props;
    

    return (
        <p onClick={props.crossedItemOnClick} id={id} className={className} style={{textDecorationLine: 'line-through'}}>{info}</p>
    )
}

export default Para;

My whole page disappears if I change it to:

        <p onClick={props.crossedItemOnClick} id={id} className={className} style={state && {textDecorationLine: 'line-through'}}>{info}</p>

I'd love to know what I'm doing wrong and why the page completely disappears. And of course explanation to learn if you'd be kind to. Much thanks!

Upvotes: 0

Views: 939

Answers (3)

shehab shalan
shehab shalan

Reputation: 26

Your approach is mostly correct, however, your condition should be applied on the style property directly like this if you want to use &&

style={{textDecorationLine: state && 'line-through'}}

Upvotes: 1

Milos Pavlovic
Milos Pavlovic

Reputation: 1450

That is because style prop expect object of type CSSProperties, and in case when your condition is false you will end up with something like style={false} which will cause your app to crash since you provided HTML element with invalid styling.

Easiest solution is to just rewrite that part to style={state ? {...someStyle} : {}}

Upvotes: 3

Shikhar Awasthi
Shikhar Awasthi

Reputation: 1232

style attribute takes object as value in react. Correct way will be:

<p onClick={props.crossedItemOnClick} id={id} className={className} style={state ? {textDecorationLine: 'line-through'}:{}}>{info}</p>

assuming you have to apply the style when state is true.

Upvotes: 2

Related Questions