I'm attempting to consume a nested prop value, then use that value to dynamically fetch another prop. This works for shallow (first level) props, but it fails when the prop is nested.
function DynamicContent(props) {
const content = props.data[props.children]
return <span>{content}</span>
}
Works (returns "My Post Title):
{
children: ["postTitle"],
data: {
postTitle: "My Post Title",
category: {
title: "The Category Title",
}
}
}
Does NOT work (returns undefined, expect "The Category Title"):
{
children: ["category.title"],
data: {
postTitle: "My Post Title",
category: {
title: "The Category Title",
}
}
}
You are doing great, you have done right. You need just a simple tweak.
Using eval
you can evaluate as much nested as you want.
const path = 'props.data' + props.children;
const content = eval(path);