The values iterated by .map() do not reflect inside the function in html attribute

Viewed 42

In the Parent component, [0, 1, 2, 3, 4, 5] values are passed and for each value a Child component is created. So there are 6 occurrences of the Child component. The child component is a bootstrap modal as below

import "../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import React from "../../node_modules/react";

function Child(props) {
  return (
    <>
      <h1 className="text-white">{props.monthpassed}</h1>
      <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#exampleModal">
        Click to open below Modal
      </button>

      <div class="modal fade text-white" id="exampleModal" data-bs-backdrop="static" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Select project and add an allocation</h5>
              <button type="button" class="btn-close btn-close-white btn-sm" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <form>
                <div class="mb-3">
                  <h1 className="text-white">{props.monthpassed}</h1>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </>);
}

export default Child;

Note that there are two instances where props.monthpassed is present. Once above the button and once on the actual modal that will be displayed when that button is clicked.

The Parent component is as below.

import "../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import React from "../../node_modules/react";
import Child from "./Child";

function Parent(props) {
  return [0, 1, 2, 3, 4, 5].map(xx => <Child monthpassed={xx}></Child>);
}

export default Parent;

When the parent component is displayed, it will be displayed like below.

Parent component displayed

Notice that above each button, the passed props.monthpassed is displayed properly based on the values in the array in the Parent component. This works perfectly.

But when I click on any of the buttons, the modal displays only one value 0 inside the modal, as opposed to the values in the array as displayed in the parent component.

Child component displayed

How do I handle this discrepancy?

1 Answers

You forgot to write return for the map.

months.map((month, month_idx) => {
    return (
        <ProjectSelectionModal
            key={month_idx}
            onSelectingProject={(project) => selectProjectHandler(month_idx)}>
        </ProjectSelectionModal>
    );
});
Related