How to correctly type component props (React) to receive (a and b) or (c and d)

Asked

Viewed 30 times

0

An opinion/tip on the typing of props:

Context: An app/site with a list of podcasts in the home, dynamic page for each podcast individually, and in both, play buttons, that plays the relevant podcast, in a global player scope.

I wanted to make the play button a separate component, not to repeat so much code

export function PlayButton ({ episodeList, index, playerFunction } ) {
  return (
    <button
      className={styles.playButton}
      type="button"
      onClick={ ()=>playerFunction(episodeList, index) }
    >
      <img src="/play.svg" alt="Tocar episódio" />
    </button>
  )
}

//...
<PlayButton episodeList={episodeList} index={index} playerFunction={playList} />

But when it comes to separating the "play full list" features from the home, and "just play this" page of each podcast, as the buttons behave differently, it got a little more complicated.

A first way I did, on the page of each episode, works, but I thought it might have a "semantic" half bad:

// passa uma lista com só um episodio
// e explicitamente toca o primeiro
<PlayButton episodeList={[episode]} index={0} playerFunction={play} />

now I’m trying to refactor this, to have a "touch button" component, which can both receive only an episode or a list.

first question: I should do this? Or the best practice is to actually have a different boot for each type of functionality?

If it is appropriate/acceptable to have this "multi-functional", what would be the best way to do that?

I tried a few ways, but all I get is trouble with Typescript accusing lack of properties in JSX, or excess in component function. Even the app running normal. The schema would be the component receiving attributes: (Foot and function play) OR (episodeList and index and function playlist)

what I thought would be the most correct, according to a survey would be:

type PlayOneButtomProps = {
...
}
type PlayListButtomProps = {
...
}
type PlayButtonProps = PlayOneButtomProps | PlayListButtomProps;

But there’s always this Typescript accusation. What is wrong with my creation of types? How should I?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.