freeCodeCamp/guide/english/certifications/data-visualization/data-visualization-with-d3/change-styles-based-on-data/index.md

1.6 KiB

title
Change Styles Based on Data

Change Styles Based on Data

Remind yourself once again what is the callback function with this

There is two ways you can complete this part, either with if-else logic or ternary operator.

if-else logic

An example from w3school


const money = 50;

if (money < 50) {

  return "I\'m rich";

}

else {

  return "I`'m poor";

}

What you need to remember is the bracket that the if-else logic associate with, (argument) and {statement}

Try Yourself Now 👩‍💻👨‍💻

Ternary operator

A more detailed explanation here. Ternary operator is a lot more concise and quicker to remember for a simple true or false statement. Read this


condition ? value if true : value if false 

For someone who still not sure here is a solution by using If-else statement

      .style("color", (d) => {
        if (d < 20){
          return 'red'
        }
        else {
          return 'green'
        }
      })