0

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",
    }
  }
}
bzmills
  • 19
  • 7

2 Answers2

0

You cannot do this, but a simple solution is to make something like this :

children: ["category", "title"]

And inside your function :

const content = props.data[props.children[0]][props.children[1]]

I assume, is not better solution but you have an idea for achieve what you want, maybe you can split into two functions one for access property inside object, and the second for access to sub child into object

KolaCaine
  • 2,037
  • 5
  • 19
  • 31
0

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);
Anurag Yadav
  • 294
  • 1
  • 9
  • This does in fact solve my problem at hand, thanks. However, I'm curious about your thoughts on using `eval()` in this situation given it's security issues. https://alligator.io/js/eval/ – bzmills May 06 '20 at 18:42
  • Yes, thanks for pointing out for readers( I know the security issues,) but at that time thinking about your situation, i didn't tell you about this . Happy Coding ;-) – Anurag Yadav May 08 '20 at 05:41