Search code examples
javascriptreactjsstatereact-functional-component

How do I render a component with the value of a state variable which is incremented with each render?


I have a component in my React App.

I am looking to render this component repeatedly a number of times. The component has a className, which I want to set for each component with the value of the 'startOrFinishCellCount' state. With each render the value should be incremented by 1.

I have tried a number of ways to do this, which have either led to infinite loops, or each component being rendered with the same state value.

How do I achieve what I have mentioned? Am I misunderstanding something about React?


import React, { useEffect, useState } from 'react';
import './TimeUserInputTableData.css'

function TimeInputCell(props) {
  const [inputValue, setInputValue] = useState('');
  const [startOrFinishCellCount, setStartOrFinishCellCount] = useState(0);

  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  return (
    <td rowSpan={props.rowSpan} colSpan={props.colSpan}>
      <input
        type="time"
        value={inputValue}
        onChange={handleInputChange}
        id='timeInputCell'
        className={`timeInputCell${startOrFinishCellCount} h-100 w-100 d-flex justify-content-between align-items-center`}
      />
    </td>
  );
}

export default TimeInputCell;


Solution

  • You can't rely on the number of times a component is rendered – React is at leisure to call your component as many times as it likes.

    Instead, if you need to e.g. render the same component multiple times, say for each day of the week, and you'd want each of them to have a different className, you'd pass in that index from the component rendering that component:

    const days = [0, 1, 2, 3, 4, 5, 6];
    function WeekDisplay() {
      return (
        <>
          {days.map(day => <DayDisplay day={day} key={day} />)}
        </>
      );
    }
    
    function DayDisplay({day}) {
      return <div className={`day-${day}`}>Day {day + 1}</div>;
    }
    

    etc.