0

I try to create a table with two arrays in a state(week_today, week_count) and a repeating sentence when rendering. I don't know how to use map() function . Please advise.

my code

    render() {
        const {week_today, week_count} = this.state; // this.state in my array put



        return (
            <div>

                <table class="table">
                    <thead class="thead-dark">
                        <tr>
                            <th scope="col">today</th>
                            <th scope="col">count</th>
                        </tr>
                    </thead>
                    <tbody>
                     //<== here my array table


                    </tbody>

                </table>
            </div>

        )
    }

use my arrays

week_today = [ 01,02,03,04,05]
week_count = [ 1,2,3,4,5]
1
  • 2
    React has good documentation on creating lists Commented Feb 14, 2020 at 8:56

2 Answers 2

5

Try below. Just a sample code

  constructor(props) {
    super(props);
    const week_today = ['01', '02', '03', '04', '05'];
    const week_count = [1, 2, 3, 4, 5];

    this.state = {
      week_today: week_today,
      week_count: week_count
    };
  }
  render() {
   const {week_today, week_count} = this.state; // suggest you to use destructuring your variables:
    return (
      <div>
        <table class="table">
          <thead class="thead-dark">
            <tr>
              <th scope="col">today</th>
              <th scope="col">count</th>
            </tr>
          </thead>
          <tbody>
            {week_today.map((today, index) =>
                <tr key={index}>
                  <td>{today}</td>
                  <td>{week_count[index]}</td>
                </tr>
            )}
          </tbody>

        </table>
      </div>
    )
  }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Just sample but diff for me!
1

Slightly changed the data structure (add this to your state):

week: [
 { today: '01', count: 1 },
 { today: '02', count: 2 },
 { today: '03', count: 3 },
 { today: '04', count: 4 },
 { today: '05', count: 5 }
]

And add this to your render:

<tbody>
  {this.state.week.map( element => {
      return (
        <tr>
          <td>
            {element.today}
          </td>
          <td>
            {element.count}
          </td>
        </tr>
      )
    })
  }
</tbody>

Comments

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.