vbotio
vbotio

Reputation: 1684

reusable react component timeline

I am building a timeline component which currently is used for measuring a day (24 hrs). I have the intention to use it as a "global" timeline, being used to measure 24 hrs, 7 weeks or 12 months.

Here is what I have

bullets(number) {
  const points = [...Array(number)].map((_, i) => {
    return (
      <li key={i} data-pop={i < 13 ? i + ' AM' : i-12 + " PM"}></li>
    )
  })
  return points;
}

render() {
  return (
    <Time>
      <ul>
        {this.bullets(24)}
      </ul>
    </Time>
  )
}

and I have the following result passing 24 or 7 in my function

timeline

My doubt is how to change the "data-pop" (which is the legend of each bullet when hovered), depending on the value I pass on my function (7, 12 or 24). How can I do that ?

Upvotes: 0

Views: 376

Answers (1)

Matt Way
Matt Way

Reputation: 33209

I wouldn't alter the legend based on the value, as it makes no semantic sense. There are a couple of options that might work for you. One would be to have props for the number of bullets, and another for how to generate the text from those numbers. For example:

const TimeLine = ({ totalBullets, legendFunc }) => (
  <Time>
    <ul>
      {[...Array(number)].map((_, i) => (
        <li key={i} data-pop={legendFunc(i)}></li>
      ))}
    </ul>
  </Time>
)

// use like this
<TimeLine 
  totalBullets={24} 
  legendFunc={i => (i < 13) 
    ? i + ' AM' 
    : i-12 + ' PM'
  }
/>

A better way though, is to make your component completely data driven. In your case this could simply be an array of text representation, but it would probably make sense to be an array of objects, so that you could have different keys for things, should the need arise. For example, start by defining the data you want to display:

// generate your bullet data somewhere
const data = [...Array(number)].map((_, i) => ({
  legend: i < 13 ? i + ' AM' : i-12 + ' PM'
}))

const TimeLine = ({ bulletData }) => (
  <Time>
    <ul>
      {bulletData.map((bullet, i) => (
         <li key={i} data-pop={bullet.legend}></li>
      ))}
    </ul>
  </Time>
)

// use like
<TimeLine bulletData={data}/>

Upvotes: 1

Related Questions