0

I am trying to display match stats boxes using bootstrap grids. Total 16 grids 4X4 i.e each row contains 4 columns. Instead of creating 16 match stats boxes is there any way to dynamically populate the data using ReactJS.

In app.js :

import React, { Component } from 'react';
import './App.css';
import Navbar from './components/navbar';
import Content from './components/content';
import Pagination from './components/pagination';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Navbar/>
        <Content/>
        <Pagination/>
      </div>
    );
  }
}

export default App;

In Content.js:

import React, { Component } from 'react';
import './content.css';

class Content extends Component {
    constructor(props){
        super(props);
        this.state = {
            matches:[],
            loading:true
        };
    }

    componentDidMount(){
        fetch('api/matches')
        .then(res => res.json())
        .then(res => {
      console.log(res)
      this.setState({
        matches:res,
        loading:false
      })
    })
    }

    render() {
        if (this.state.loading) {
            return <div>>Loading...</div>
        }

    return (
      <div>
          <div class="row">

            <div class="col-lg-3">
                <div id="one">
                    <p class="match">Match {this.state.matches[0].id}</p>
                    <p><h4>{this.state.matches[0].team1}</h4></p>
                    <p>VS</p>
                    <p><h4>{this.state.matches[0].team2}</h4></p>
                    <div class="winner">
                        <p><h3>Winner</h3></p>
                        <p><h4>{this.state.matches[0].winner}</h4></p>
                    </div>
                    <div class="stats">
                    <button type="button" class="btn btn-primary">View Stats</button>
                    </div>
                </div>
            </div>
          </div>
      </div>
    );
  }
}

export default Content;

In content.js there is only 1 match stats box and instead of hard coding 16 boxes how can I prevent code redundant code in render function.

Current view of my web app:

enter image description here

2 Answers 2

2

You can split your code into separate Table, Row, and Cell components. That way you can add your data to Table and it can feed the appropriate data to the rows, and the rows can feed appropriate data to the cells.

Here's a rough example to get you started:

function Table({data}) {
  return (
    <table>
      {data.map(row => <Row data={row} />)}
    </table>
  )
}

function Row({data}) {
  return (
    <tr>
      {data.map(cell => <Cell data={cell} />)}
    </tr>
  )
}

function Cell({data}) {
  return (
    <td>{data}</td>
  )
}

const data = [
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12]
];

ReactDOM.render(
  <Table data={data} />,
  document.getElementById('container')
);
table {
  border-collapse: collapse;
  border: 1px solid #454545;
}

td {
  padding: 5px;
  border: 1px solid #dfdfdf;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks got it. So in this way can I populate my bootstrap grids because total number of columns for bootstrap grids is 12 ?
Sure, I guess you can do what you want. I think the best thing first is to make sure the format of the data is suitable for the project. So if it's just a single array of elements maybe think of changing it so it's a an array of arrays n columns in length like I have in the example. That makes it easier to build the components.
The data which I want to populate is arrays see screenshot : imgur.com/a/puaAj is your method suitable for my JSON data.
That's an array of objects. So I'm assuming that you want each object's information as one row in the table? If you add that data to a jsfiddle I can take a look.
Then just arr.slice(0, 16) the part of the array you want to display and pass that in as the data. As for the rest, I expect you can work it out given the information in the answer.
|
1

you can use the map function. Please check the code below:

import React, { Component } from 'react';
import './content.css';

class Content extends Component {
    constructor(props) {
        super(props);
        this.state = {
            matches: [],
            loading: true
        };
    }

    componentDidMount() {
        fetch('api/matches')
            .then(res => res.json())
            .then(res => {
                console.log(res)
                this.setState({
                    matches: res,
                    loading: false
                })
            })
    }

    renderMatches() {
        return this.state.matches.map(match => {
            return (
                <div class="col-lg-3">
                    <div id="one">
                        <p class="match">Match {match.id}</p>
                        <p><h4>{match.team1}</h4></p>
                        <p>VS</p>
                        <p><h4>{match.team2}</h4></p>
                        <div class="winner">
                            <p><h3>Winner</h3></p>
                            <p><h4>{match.winner}</h4></p>
                        </div>
                        <div class="stats">
                            <button type="button" class="btn btn-primary">View Stats</button>
                        </div>
                    </div>
                </div>
            );
        })
    }

    render() {
        if (this.state.loading) {
            return <div>>Loading...</div>
        }

        return (
            <div>
                <div class="row">
                    {this.renderMatches()}
                </div>
            </div>
        );
    }
}

export default Content;

5 Comments

I want to display 16 boxes i.e 4X4 so do I need to write {this.renderMatches()} 16 times. As you can see in my code column size is 3 which should add upto 12 i.e 4 boxes.
{this.renderMatches()} will create 16 div with class col-lg-3 as we are using the map function for the looping.
Total 577 JSON objects are returned(matches[0],matches[1]....matches[576]) so when will map stop lopping.
The second parameter passed to map function is index. So we can have a logic where we check the page no. and current index to show the 16 matches for the current page.
I did not get what you said. Which second parameter to map function ? Also I could not understand this line -> So we can have a logic where we check the page no. and current index to show the 16 matches for the current page

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.