Search code examples
javascriptreactjsif-statementconditional-operatorternary

Using a ternary expression in React


In this component:

 const MovieComponent = (props) => {
  const { Poster, Price, Title, cinemaWorldPrice } = props.movie;

  return (
    <MovieContainer>
      <CoverImage src={Poster} alt="" />
      <MovieName>{Title}</MovieName>

      <InfoColumn>
        <MovieInfo>FilmWorld: ${Price}</MovieInfo>
        <MovieInfo>CinemaWorld: ${cinemaWorldPrice}</MovieInfo>
      </InfoColumn>
    </MovieContainer>
  );
};

I'm wanting to write a ternary expression that will change the font color of:

<MovieInfo>FilmWorld: ${Price}</MovieInfo>
        <MovieInfo>CinemaWorld: ${Price}</MovieInfo>

Something basically saying

if (Filmworld Price > CinemaWorld Price) { Filmworld Price = color: "green"}

and vice versa. Is this possible? And would the code be in the movie info section? This is on React.


Solution

  • You need to

    • properly interpolate the prices into JSX (${} is only for template literals)
    • surround the price texts in another element, like a span, so you can then conditionally color that span if needed
    const MovieComponent = (props) => {
        const { Poster, Price, Title, cinemaWorldPrice } = props.movie;
        return (
            <MovieContainer>
                <CoverImage src={Poster} alt="" />
                <MovieName>{Title}</MovieName>
                <InfoColumn>
                <MovieInfo>
                        FilmWorld:
                        <span style={Price > cinemaWorldPrice ? { color: 'green' } : null}>{Price}</span>
                    </MovieInfo>
                    <MovieInfo>
                        CinemaWorld:
                        <span style={Price < cinemaWorldPrice ? { color: 'green' } : null}>{cinemaWorldPrice}</span>
                    </MovieInfo>
                </InfoColumn>
            </MovieContainer>
        );
    };