Tags:  cssreactjs
Source:  Twitter logo

I can style a table in react via:

  var tableStyle = {
       "border": "1px solid black"
    };
    return (
      <div>
        <h1>My Awesome Table</h1>
        <table style={tableStyle}>
          <th>Awesome Header</th>

Coupling my style and html into a reusable component is the react way of doing things. How can I effectively style my whole table? I could style each header via:

<th style={headerStyle}>
<th style={headerStyle}>
<th style={headerStyle}>

and

<tr style={rowStyle}>
<tr style={rowStyle}>

That's not very efficient. In plain old CSS I can just do

 table {
       //boom style all the things
    }
    th {

    }
    tr {
    }

Using CSS, particularly in a SPA application can become a maintenance headache. So I like the idea of sticking my style into this component where nobody else will inherit it. How can I do it without writing a bunch of repetitive code?

Not entirely sure I understand what you're looking for, but you want a better way of having css and markup in one file with no external dependencies?

If so, this might work:

return (
  <style>{`
    table{
     border:1px solid black;
    }
  `}</style>
  <div>
    <h1>My Awesome Table</h1>
    <table>
      <th>Awesome Header</th>
      ...
)

Using template literal string formatting seems necessary here to support the <style> contents to span across multiple lines.

Alternatively:

<style>{"table{border:1px solid black;}"}</style>
6 users liked answer #0dislike answer #06
Chris profile pic
Chris

define style in your global theme.js

 "table, th, td" :{
      border: "1px solid white" },

      "th, td" : {
        textAlign: "center"
    },

All tables in App will now display white border

1 users liked answer #1dislike answer #11
Hitesh Sahu profile pic
Hitesh Sahu

You should have all of your styles in a separate folder/ and file and maintain separation of concerns. No CSS declarations should be in your JavaScript. If must style your components, you should be using CSS classes instead of inline-styles.

Then you could style all of your tables from one CSS file.

/*CSS file*/

table.myAwesomeTable {
  ...code
}

/*Markup */
<table className="myAwesomeTable">

</table>
0 users liked answer #2dislike answer #20
bullzito profile pic
bullzito

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).