Inline styles for tables in ReactJS/JSX

Sam picture Sam · Jun 6, 2018 · Viewed 8.1k times · Source

Hi I'm having trouble adding inline styling to table components in React. Basically what I'm trying to do is so that the table header/cells are divided equally spacing so I'm adding width: '50%' styling to make this work. I added in the console and it works, but when I return to add it in my code, it doesn't.

I tried adding it to anything just to see if it work and it doesn't. Is there something I'm missing?

What it looks like:

What it looks like

What I want it to look like (after adding width styling to console): Width 50%

JSX:

                    <table className="table table-striped">
                        <thead>
                            <tr styles={{width: '50%'}}>
                                <th styles={{width: '50%'}}>Hello</th>
                                <th styles={{width: '50%'}}>World</th>                                
                            </tr>
                        </thead>
                        <tbody>
                            {(data.length == 0)&&           
                                <tr>
                                    <td>I'm</td>
                                    <td>Sam</td>
                                </tr>
                            }
                        </tbody>
                    </table>

Answer

Chase DeAnda picture Chase DeAnda · Jun 6, 2018

You can use table-layout: fixed; width: 100% on the table to force equal column widths:

table {
  width: 100%;
  table-layout: fixed;
}
table tr th {
  text-align: left;
  background: gray;
  color: white;
}
                    <table className="table table-striped">
                        <thead>
                            <tr style={{width: '50%'}}>
                                <th style={{width: '50%'}}>Hello</th>
                                <th style={{width: '50%'}}>World</th>                                
                            </tr>
                        </thead>
                        <tbody        
                                <tr>
                                    <td>I'm</td>
                                    <td>Sam</td>
                                </tr>
                        </tbody>
                    </table>

Your width: 50% isn't working most likely because your parent .table doesn't have a width set. You can try adding width: 100% to the table and then your 50% might work.

EDIT As other users have mentioned, change styles to style as well.