skip to Main Content

I want a set up an Array of items, that have various properties, as a Prop on my component.

I’m trying to pass an array of items with different properties to a component, so, let’s say that this is my array of objects:

`  let recepies = [
    {
      name: "A Name",
      imageURL: "V",
      difficulty: "C",
      time: 12,
      categories: "c",
    },
    {
      name: "aa",
      imageURL: "bb",
      difficulty: "cc",
      tieme: 13,
      categories: "c",
    }]
`

When I get to my Component, how do I define the Props?
I guessed

`interface Props {
    recepies: Object[];}

`should work, but when I get to:

    return(recepies.forEach(function (recipe) {

<RecepieCard
      name={recipe.namme}

I get that the property doesn’t exist on the object. How should I go about doing this?

2

Answers


  1. you shod define and assign type to your object like this

    type TRecepies = {
      name: string;
      imageURL: string;
      difficulty: string;
      time: number
      categories: string;
    }
    
    let recepies: TRecepies[] = [
    {
      name: "A Name",
      imageURL: "V",
      difficulty: "C",
      time: 12,
      categories: "c",
    },
    {
      name: "aa",
      imageURL: "bb",
      difficulty: "cc",
      tieme: 13,
      categories: "c",
    }]
    

    and assign your object

    interface IProps {
     recepies: TRecepies[];
    }
    

    then use them on your component and Be careful type correct property of your object

    return(recepies.forEach(function (recipe) {
    <RecepieCard
      name={recipe.name}
    

    name no namme

    Login or Signup to reply.
  2. The interface is only the specififing the structure of the props.
    You have to pass the Props to your component.

    type Recepy = {
      name: string,
      imageURL: string,
      difficulty: string,
      tieme: number,
      categories: string,
    }
    
    type Props = {
      recepies: Recepy[];
    }
    
    // as class component
    class MyComponent extends Component<Props> {
      render() {
        const { recipes } = this.props;
        return recipes.map(recipe => (
          <RecipeCard
            key={i}
            name={recipe.name}
          />
        ));
      }
    }
    
    // or functional component
    function MyComponent({recepies}: Props) {
      return recepies.map(
        (r, i) => (<RecepieCard
          key={i}
          name={recipe.namme}
        />)
      )
    }
    

    https://react.dev/learn/passing-props-to-a-component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search