Bostjan Bostjan - 2 months ago 19x
React JSX Question

Render table with react after acquiring data through JS

I have a problem while trying to display data with React. The data is first calculated in a normal JS function and isn't ready by the time React renders its' table...

this is the call to a JS function:

<script type="text/javascript">

The function determines round robin pairs (config.pairs is the global variable for them) for a simulated football league. I would like to display those pairs in a React rendered table.

This is the React code for table rendering...

var Table = React.createClass({

getInitialState: function() {
return {data:};

render: function() {
var headerComponents = this.generateHeaders(),
rowComponents = this.generateRows();

return (

generateHeaders: function() {
var cols = this.props.cols; // [{key, label}]

// generate our header (th) cell components
return {
return <th key={colData.key}>{colData.label}</th>;

generateRows: function() {
var cols = this.props.cols, // [{key, label}]
data =;

var dataMap = {

return {
// handle the column data within each row
var cells = {
// colData.key might be "firstName"
return <td> {item[colData.key]} </td>;
return <tr key={}> {cells} </tr>;

ReactDOM.render(<Table cols={columns} data={config.pairs}/>, document.getElementById('roundPairs'));

Now I understand why config.pairs is empty by the time React renders, I would need some help on how to pass those values to React when they are calculated...please help if you can.


You have three options.

The first one is to delay the rendering of the Table component until the data is ready. This could be achieved by passing the rendering code as a callback to the derivePairs function. Personally, I find this a really clumsy way of achieving the desired result.

The other way is to use life cycle methods of React components. In your case componentWillMount makes the most sense. You can run the code that gets your data here and when it's available, you can set the state accordingly and React will re-render your component with the new data. This is a nice solution to your problem but it also binds the data fetching logic to your Table component. This could or could not work depending on your design and future needs.

The best way to do it in my opinion is to create another component that actually wraps the Table component. It will manage data fetching itself and pass the relevant data to the Table component. This way your Table component will not need to know how to fetch its data and it will correctly render with the data you pull/generate.