1

In Home.js I have the following code

<div id="sub-container">
...
</div>

and in home.css I have the following code

#sub-container {
    ... // A lot of css
}

I want to conditionally add one value to the css. The only solution I found is to create a new block and add the line there

{condition ? (<div id="sub-container">) : (<div id="sub-container-2">)

#sub-container-2 {
    ... // A lot of css
justify-content: flex-end;
}

Is there another solution to optimize the code?

4 Answers 4

2

you can do this

<div id={condition ? 'sub-container' : 'sub-container-2'}></div>
Sign up to request clarification or add additional context in comments.

Comments

0

Why don't use an extra class ?

.sub-container-extra { justify-content: flex-end; }

And in component

<div id="sub-container" className={condition && 'sub-container-extra'}></div>

Comments

0

Add a class to your sub-container-2 element:

<div id="sub-container-2" class="justify-flex-end">

Add set the styles as follows:

#sub-container, #sub-container-2 {
    /* ... A lot of css */
}

#sub-container-2.justify-flex-end {
    justify-content: flex-end;
}

This works by applying all your global styles to both tags, and the extra style to only the tag with the specified class.

Comments

0

Maybe instead of duplicating class, You can customize the main one

#sub-container {
    ... // A lot of css
    ... // A lot of css
    ... // A lot of css
}

#sub-container.special {
    justify-content: flex-end;
}

And then just add the class to the div conditionally:

<div id="sub-container" {condition ? 'class="special"' : ''}></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.