Hello is there a way to make it less repetetive? It is React with typescript. On the given type I would like to input correct image.
import { Box, Heading, Image, Text, Button, Icon } from "@chakra-ui/react";
import { Link } from "react-router-dom";
import { Recipe } from "../../shared/types/Recipe";
import Breakfast from "../../images/Breakfast.jpg";
import Lunch from "../../images/Lunch.jpg";
import Dinner from "../../images/Dinner.jpg";
import Supper from "../../images/Supper.jpg";
import { FaHeart } from "react-icons/fa";
import { useState } from "react";
const RecipeItem: React.FC<Recipe> = (props) => {
const [isLiked, setIsLiekd] = useState < boolean > false;
const onClickHandler = () => {
setIsLiekd(true);
};
let imgName;
if (props.type === "Breakfast") imgName = Breakfast;
if (props.type === "Lunch") imgName = Lunch;
if (props.type === "Dinner") imgName = Dinner;
if (props.type === "Supper") imgName = Supper;
// ...
};
CodePudding user response:
Since the type name in props.type
is the same as the variable name for the image, you can use the object shorthand syntax for a very succinct:
const imgName = ({Breakfast, Lunch, Dinner, Supper})[props.type];