skip to Main Content

I have got problem. When i am writing this code to change font color based of plus or minus number i am getting error

Cannot read properties of null (reading ‘style’)
TypeError: Cannot read properties of null (reading ‘style’)

I tried everything but it doesnt work. Can anyone help me solve this problem?

Code for the component with numbers in table:

<td className="">
                    {props.coins.map(coins => {
                        
                        if (coins.price_change_percentage_24h > 0) {
                            var x = document.getElementById('percent')
                            x.style.color = 'red'
                        } else {
                            var x = document.getElementById('percent')
                            x.style.color = 'green'
                        }

                        return (
                            <div id='percent' className="flex flex-col border-b py-6 h-[73px] mx-[-2px] px-2">
                                {coins.price_change_percentage_24h.toFixed(2)}%
                            </div>
                        )
                    })}
                </td>

I tried everything. Hope someone could help me.

2

Answers


  1. example code

    you should try to use style attribute like this one. I think it will work. Like this:

    style = { (coins.price_change_percentage_24h > 0) ? { color: "red" } : { color: "green" } }

    Login or Signup to reply.
  2. Your real issue is your approach. So lets forget about your syntactical errors, and approach this differently.

    Just use an inline style with a ternary argument. You are overcomplicating it with if statements and query selectors.

    props.coins.map(coins => {
            return (
                <div id='percent'
                     className="flex flex-col border-b py-6 h-[73px] mx-[-2px] px-2"
                     style={{
                     color: (coins.price_change_percentage_24h > 0) ? "red" : "green"
                     }}>
                    {coins.price_change_percentage_24h.toFixed(2)}%
                </div>
            )
        }
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search