0

I have to write a condition for showing style on my div but I am making some mistake due to which it is not working properly. Please help me to correct this syntax. This is my code

<div
style={item.settings && 'backdropSettings' in item.settings ? { 
item.settings.backdropSettings.value.includes('#') ? 
{background:item.settings.backdropSettings.value} :
{backgroundImage: `url(${item.settings.backdropSettings.value})`}
} : null}
> 
</div>
7
  • 2
    Don't. Use if/else instead. It's much clearer. Commented Dec 17, 2020 at 10:16
  • 1
    Your ternary operator is hard to read/understand. Don't use it. Use simple if {} else {} inside call of function Commented Dec 17, 2020 at 10:19
  • @Justinas yeah i can write if{} else {} statement. But I want to use ternary operator. So can help me for this. for writing syntax. Commented Dec 17, 2020 at 10:26
  • @DheerajKumar condition ? (condition ? true : false) : (false) Commented Dec 17, 2020 at 10:30
  • @Justinas but during writing my syntax I am making error during writing curly braces. make you help me to make it correct. Commented Dec 17, 2020 at 11:02

1 Answer 1

1

If you do complicated calculation do not put it in your render , put it before , it's way simpler, that's why you can't see your mistake.

Try something like this (check how it's written though, not sure it's 100% ok)

const getStyle = (item) => {
    if (item.settings && 'backdropSettings' in item.settings) {
        const { backdropSettings } = item.settings;
        
        if (backdropSettings.value.includes('#')) {
            return `backgroundImage:${item.settings.backdropSettings.value}`
        } else {
            return `backgroundImage:url(${item.settings.backdropSettings.value})`
        }
    } 
    return null
}

return(
    <div style={getStyle(item)}>
    </div> 
);

This is way more readable and you can find your mistake easily. Hope it helps.

Sign up to request clarification or add additional context in comments.

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.