P.Brian.Mackey P.Brian.Mackey - 29 days ago 6
CSS Question

How to efficiently style a table inline in react

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?

Answer

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>