Guide to bringing API information into a Material UI Card

I've been working on a Recipe app that leverages data from the edamame API. I successfully imported Material UI cards into my .js file to pull data from the API and stored it in a const named recipes. However, I'm facing difficulties in getting the data to display within the imported cards. Oddly enough, when I create local cards without Material UI, the API data displays perfectly. But as soon as Material UI is involved, issues arise. How should I go about solving this?

MealPlan.Js (API call and data storage)

import React, { useState, useEffect } from "react";
import style from "./recipe.module.css";
import "./App.css";
import NavigationBar from "./NavigationBar";
import Card from "./card";
import { Grid } from "@material-ui/core";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
    gridContainer: {
        paddingLeft: "20px",
        paddingRight: "20px",
    },
});

export default function MealPlan() {
    //  defining the useStates

    const [recipes, setRecipes] = useState([]); 
    const [search, setSearch] = useState("");
    const [query, setQuery] = useState("chicken");
    const APP_ID = "removed";
    const APP_KEY = "removed";

    useEffect(() => {
        getRecipes(); 
    }, [query]); 

    const getRecipes = async () => {
        const response = await fetch(
            `https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`
        ); 
        
        const data = await response.json();  
        setRecipes(data.hits);
        console.log(data.hits);
    };

    const MealPlanCard = ({ title, calories, image, ingredients }) => {
        const round = Math.round(calories);

        return (
            <div className={style.recipe}>
                <h1>{title}</h1>
                <img className={style.image} src={image} alt="" />
            </div>
        );
    };

    return (

                {recipes.slice(0, 1).map((recipe) => (
                    <MealPlanCard
                        key={recipe.recipe.label}
                        title={recipe.recipe.label}
                        calories={recipe.recipe.calories}
                        image={recipe.recipe.image}
                        ingredients={recipe.recipe.ingredients}
                    />
                ))}
            </div>

<Grid container spacing={4} className={classes.gridContainer}>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
                <Grid item xs={12} sm={6} md={4}>
                    <Card />
                </Grid>
            </Grid>
        </div>
    );
}

Here's the JSX code for the imported Material UI cards:

import { makeStyles } from "@material-ui/core/styles";
import Card from "@material-ui/core/Card";
import CardActions from "@material-ui/core/CardActions";
import CardContent from "@material-ui/core/CardContent";
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";

const useStyles = makeStyles({
    root: {
        minWidth: 200,
    },
    bullet: {
        display: "inline-block",
        margin: "0 2px",
        transform: "scale(0.8)",
    },
    title: {
        fontSize: 14,
    },
    pos: {
        marginBottom: 12,
    },
});

export default function SimpleCard() {
    const classes = useStyles();
    const bull = <span className={classes.bullet}>•</span>;

    return (
        <Card className={classes.root}>
            <CardContent></CardContent>
            <CardActions>
                <Button size="small">Button</Button>
            </CardActions>
        </Card>
    );
}

Check out how my page looks currently here.

The goal is to populate the imported Material UI cards at the bottom with the content of my personal card at the top. Any suggestions on accomplishing this?

Answer №1

If I understood correctly, you are looking to have your functional component SimpleCard receive data from MealPlan...

If that's what you're aiming for, here's a suggestion:

SimpleCard.js

export default function SimpleCard(props) {
    const classes = useStyles();
    const bullet = <span className={classes.bullet}>•</span>;

    return (
        <Card className={classes.root}>
            <CardContent>{props.ingredient}</CardContent>
            <CardActions>
                <Button size="small">{props.calories}</Button>
            </CardActions>
        </Card>
    );
}

In your MealPlan.js file, make sure to import SimpleCard like this:

import SimpleCard from 'pathTo/SimpleCard'

Instead of rendering Card in MealPlan.js, render SimpleCard and pass your variables as props (such as nutrition, calories...)

<Grid item xs={12} sm={6} md={4}>
      <SimpleCard 
           ingredient={"banana"}
           calories={40}
      />
</Grid>

The idea is to create reusable components like SimpleCard and populate them with the data passed through props, such as ingredient and calories.

This way, you can have multiple instances of SimpleCard with different data:

<Grid item xs={12} sm={6} md={4}>
      <SimpleCard 
           ingredient={"chocolate"}
           calories={100}
      />
</Grid>
<Grid item xs={12} sm={6} md={4}>
      <SimpleCard 
           ingredient={"banana"}
           calories={40}
      />
</Grid>

And so on!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on comparing a string against an object's value

I need to compare the key values of an object with the strings yes or no. I am encountering difficulties in achieving this comparison and updating radio buttons accordingly based on the comparison. Here is the code snippet: const screenJson = { Managem ...

Utilize React-router-dom and react-table for efficient redirection

I am currently working on implementing a redirect function within an onclick event in React-table. The onRowClick function successfully logs the header name upon clicking, but for some reason, the redirect does not work as expected after the click event. I ...

Default value in Material UI textField unable to display

This issue arises when using an updated form textField. Initially, data is fetched using the toDo id. const [toDo, setTodo] = useState<any>({}); useEffect(() => { axiosConfig .get(`/todo/${todoId}`) .then((response) => { setTodo(respons ...

Encountered an error while trying to install @material-ui/core through npm: Received an unexpected end of JSON input

npm install @material-ui/core npm ERR! Unexpected end of JSON input while parsing near '...X1F+dSMvv9bUwJSg+lOUX' npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\WR-022\AppData\Roaming\npm-cach ...

Ensuring Consistent Placement of Elements Regardless of Screen Size with CSS

I'm currently working on an Ionic App and I need to position some buttons (stacked vertically) at the bottom-left corner of the device's screen. Here is the CSS I am using: .button { left = "1em"; z-index = "13"; overflow = "scroll"; ...

What is the secret to creating a button that can sort text and another button that flips the word density in my content?

I'm not a fan of having something like this because it's displeasing to the eye: https://i.stack.imgur.com/3F4sp.jpg Instead, I prefer my word density to be more organized and structured. How can I achieve this? Sort by highest word density fi ...

Using Java beans to present form data utilizing session

How can I utilize Java Beans and session beans to store user input data and display a preview of the entered details on the next page? I have already created a servlet using JSP, but now I want to incorporate Java Beans to showcase the form data. How shoul ...

Central alignment of div with cursor

I'm experimenting with creating a unique custom cursor using a <div> that trails the movement of the mouse pointer. While the current setup works smoothly, I've noticed that when scrolling down the page, the div lags behind until the scrol ...

What is the best way to create a responsive menu in code?

I am working on creating a responsive menu. Check out cuppcomputing For the desktop version, the whole panel will be displayed when it meets the max-width: 600px (tablet and mobile size). Initially, only the title is shown, and clicking on it will reveal ...

Retrieve all user records, excluding the currently logged in user

Having trouble implementing a filter logic in my local meet app similar to Tinder. How can I display all users on the main page except for the user who is currently logged in? I've tried using the filter method but can't seem to get it right. Any ...

Tips for restoring lost data from localStorage after leaving the browser where only one data remains

After deleting all bookmark data from localStorage and closing my website tab or Chrome, I am puzzled as to why there is still one remaining data entry when I revisit the site, which happens to be the most recently deleted data. This is the code snippet I ...

When working in MongoDB, the term "undefined" is not used for data; instead, the uploaded file data is

Exploring the world of MERN, I decided to create an image uploader website. Everything was going smoothly until I encountered a problem while trying to upload an image with text input from React. Despite successful uploading of the image, the text appear ...

Issue with mouseMove function not aligning correctly with object-fit:contain CSS property

My current code allows users to select a color from an image when hovering over the pixel with the mouse. However, I am encountering an issue where the colors do not map correctly when using object-fit: contain for the image. The script seems to be treatin ...

The issue persists with `getServerSideProps` as it fails to retrieve data even when executed within the

Hey there! I'm currently facing an issue with fetching data in my Next.js app using getServerSideProps. The data is not being retrieved as expected, and I'm getting either an empty object or undefined in the console. I've tried various Next. ...

Tips for locating the highest number in JavaScript

I'm having trouble with my code where the first number, even if it's the largest, is not displaying as such. Instead, it shows the second largest number. Even when following suggestions, I encountered an issue where if the numbers are entered as ...

Different ways to create audio using GWT

Looking for ways to incorporate audio into your GWT app? I am considering creating a simple game, but it seems like there hasn't been much progress on direct audio support within GWT. This is likely due to the lack of underlying browser support, but I ...

Adjusting custom colors of a material-UI component for a seamless transition to dark mode

Hey there, I've created a customized chip component for my Material-UI app where I am able to change the background and border colors of the chips by using the grey object. However, when I switch to dark mode via the global theme palette: { type: "da ...

Error: npm command missing" encountered while deploying a Python app on Heroku

I recently set up a Heroku account and I am attempting to deploy my current code. However, when I execute the command git push heroku master, I encounter the following error: Counting objects: 348, done. Delta compression using up to 4 threads. Compres ...

How can I add a drop-down list to a cell within a table?

Can a drop-down list be added into a table cell? Thank you! Here is an excerpt of the code: $sql_query="SELECT nameOfwarning FROM warnings"; $sodss=mysqli_query($d,$sql_query); if (mysqli_num_rows($result)<1) ?> <select name = "warnings"> ...

Make sure to trigger a callback function once the radio button or checkbox is selected using jQuery, JavaScript, or Angular

I'm looking to receive a callback once the click event has finished in the original function. <input type="radio" onchange="changefun()" /> function changefun() { // some code will be done here } on another page $(document).on('input: ...