Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to efficiently style a table inline in react

Tags:

css

reactjs

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?

like image 792
P.Brian.Mackey Avatar asked Feb 05 '16 22:02

P.Brian.Mackey


2 Answers

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>
like image 124
Chris Avatar answered Sep 18 '22 23:09

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

like image 40
Hitesh Sahu Avatar answered Sep 21 '22 23:09

Hitesh Sahu