Style Specific HTML tags in React

Viewed 56

I have a table and I'm trying to style it. That's what I've done so far:

                <tr>
                    <th> </th>
                    <th style={tstyle}>Canada</th>
                    <th style={tstyle}>US</th>
                    <th style={tstyle}>Total</th>
                </tr>

and then:

const tstyle = {
border: '1px solid #dddddd',
padding: '8px',
};

This works fine but I'm sure it's a better way to do that without repeating style={tstyle}. I tried doing like:

const styles = () => createStyles({
th: {
    color: 'blue',
},

There's no errors but it's not working.

6 Answers

Avoid using inline styles. Instead add below css style in your global css file

Set id to tr element

            <tr id="tr">
                <th> </th>
                <th>Canada</th>
                <th>US</th>
                <th>Total</th>
            </tr>

For eg: app.css file

  #tr > th{
       border: '1px solid #dddddd';
       padding: '8px';
  }

If something else overrides th styles then set important

  #tr > th{
       border: '1px solid #dddddd !important';
       padding: '8px !important';
  }

So this css style will be applied across your application whoever you use th elements

How about a custom functional component?

const style = {
border: '1px solid #dddddd',
padding: '8px',
};
const StyledTh = ({children: text}) => <th style={style}>{text}</th>

Usage:

                <tr>
                    <th></th>
                    <StyledTh>Canada</StyledTh>
                    <StyledTh>US</StyledTh>
                    <StyledTh>Total</StyledTh>
                </tr>

Here is another suggestion: style it by using classes:

                    <tr>
                    <th> </th>
                    <th className={classes.tableCell} >Canada</th>
                    <th className={classes.tableCell}>US</th>
                    <th className={classes.tableCell}>Total</th>
                    </tr>

and then:

tableCell: {
    border: '1px solid #dddddd',
    padding: '8px',
  },

I will suggest using styled component. you can define something like

const TableHeader = styled.th`    
      border: '1px solid #dddddd',
      padding: '8px',
    `;

and use it like:

<TableHeader></TableHeader>
<TableHeader>Canada</TableHeader>
....

Here is the link for getting started https://www.styled-components.com/docs/basics#getting-started

Why not iterating over a styled th element?

headers = ['Canada', 'US', 'Total'];
const headerElements = headers.map(header => <th style={tstyle}>{header}</th>);

Then you call all your header elements

<tr>{headerElements}</tr>
Related