Question
In the context of this exercise , how can we access the individual elements or values of a prop which is an array or object?
Answer
When passing in a prop which is an array or an object, you can access the elements or values as you would normally.
For example, with a prop that is an array, you can access an element using the index as follows,
/* A component with an array as a prop */
<SomeComponent arr={["A", "B"]} />
/* To access the second element of the array */
this.props.arr[1]
If the prop is an object, you can access a specific value using the corresponding key,
/* A component with an object as a prop */
<SomeComponent obj={{key: "value"}} />
/* To access the value of the key */
this.props.obj["key"]
12 Likes
jephos249:
this.props.obj["key"]
why is key inside a bracket? Its not an array right? did i miss something?
Yeah, even i have the same doubt. I think it should be accessed like this.props.obj.key but iam not sure.
rd9911
January 26, 2021, 6:58am
4
This is another way to access values of objects.
const obj = {name: 'james'};
console.log(obj.name)
// james
console.log(obj[name])
// james
4 Likes
Object properties must also be accessed this way if the name of the property contains spaces or special characters. You can also use variables to pass in property names dynamically, which is also not possible using dot notation.
var myProp = "foo";
object[myProp]
1 Like
weeshin
September 29, 2021, 8:23am
7
I think the second method in your post should be:
console.log(obj['name'])
1 Like