0

I'm trying to add a style to a html element only when the property of an array of object has a certain value. but I got an error like this instead:

/src/App.js: Unexpected token, expected "..." (35:25)

here's my code: codesandbox

export default function App() {
  const data = [
    {
      id:1,
      score:10,
    },
    {
      id:2,
      score:20,
    },
    {
      id:3,
      score:50,
    }
  ];

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      {
        data.length > 0
        ? (
          <table>
            <thead>
              <tr>
                <th>No.</th>
                <th>value</th>
              </tr>
            </thead>
            <tbody>
              {
                data.map((item, index) => (
                  <tr key={item.id}>
                    <td>{index+1}.</td>
                    <td {item.value > 10 ? 'style=\'backgroundColor:"red"\'' : ''}>
                      {item.value}
                    </td>
                  </tr>
                ))
              }
            </tbody>
          </table>
        )
        : (
          <div>
            <em>No data</em>
          </div>
        )
      }
      {
        data.map((item, index) => (

        ))
      }
    </div>
  );
}
1
  • You’re trying to set a property of the table data element but you’re just putting a string there instead. Use an object and spread it into the TD props, or set the style value and use it in an object. Commented Jul 31, 2022 at 17:02

1 Answer 1

1
<td style={item.value > 10 ? { backgroundColor: "red" } : ""}>

The style attribute in React accepts a JavaScript object with camelCased properties rather than a CSS string. You can find more details here.

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.