This September, we're launching new AWS Amplify Studio features each week. Today we're launching nested components. I'm going to add a component with nested data to a recipe app, if you're new to Amplify Studio check out that full tutorial first!
First, let's add a second model to the app. We'll make the recipe app social and add comments. I'll add a Comment model with the fields author, text, and date. All will be strings except the date which will be an AWSDate. Add a relationship to the Recipe model where one recipe has many Comments. I'll rename the relationship to have a lower case c in Comments. Then click "Save and Deploy."
I'll create a few comments within the Content
tab.
Now, in Figma, I'll create a comment component that displays that username, date, and comment text. You can always get back to your Figma file by clicking "Edit Component in Figma" in the configuration view for any component.
Now, I'll go to the UI Library tab and select the comment Component. I'll set the username to the comment.author
, the date to the comment.date
, and the comment text to comment.text
.
Then, I'll create a collection for the comments. I'll call the collection CommentCollection
. I'll also add a component slot to the bottom of the Recipe detail component so that I can embed the comment list below each recipe. I'll call the slot commentlist
.
I'll sync my changes locally by running amplify pull
in my local project.
In my [id.js]
page, I'll query to get all of the comments that belong to the recipe rendered on the page. I'll also pass the comments to the RecipeDetail component.
export async function getStaticProps(context) {
const SSR = withSSRContext({ context });
console.log(context);
const recipe = await SSR.DataStore.query(RecipeModel, context.params.id);
const comments = await SSR.DataStore.query(Comment, c => c.recipeID("eq", recipe.id))
return {
props: { recipe: serializeModel(recipe), comments: serializeModel(comments) },
}
}
Then, I'll pass that CommentCollection
to my component slot. I'll pass the filtered comments as the data set so that only the ones that belong to the recipe are rendered.
export default function RecipeDetail({ recipe, comments }) {
return <Recipe recipe={recipe} similarrecipes={
<h2>Similar Recipes</h2>
} commentlist={
<CommentCollection comments={comments} />
}/>;
}
Conclusion
You can now add components with nested data to your Amplify Studio-generated components. Use this feature today in your Amplify Hackathon project, we'd love to see how you use it!