I'm working on a React app and want the component I'm working on to be able to access the key names in the props object the component is receiving.
For example, I have this object:
var fido = {
animal: "dog",
legs: 4,
licksSelf: true
}
I then pass this object via the props object to my React component:
<Pet characteristics={fido} />
Then in my React component for Pet, I want to access both the key and the value, how might I do that? For example, in this following incorrect code:
class Pet extends React.Component {
render () {
var petList = this.props.characteristics.map((char) => {
return (
<div>{char.key} : {char.value}</div> // <-- what should this code look like?
);
};
return (
<div>{petList}</div>
);
};
};
Does anyone know how I access the names of the keys in the key-value pairs on the props object? Thanks!
entries() is another way to extract the number of key-value pairs from the props object. Below is some simple syntax. You need to pass the name of the object along with the function Object. entries() , which gets the key-value pair, and afterward you can use those known keys and values as demonstrated below.
You can do it this way: import React from "react"; export default props => { console. log(props. tablevalue); const ths = props.
If we want to access all the values of nested objects then we have to use recursion to access each and every level of that object. And it can get more complicated according to the nesting of the object. That why we have to use recursion to get all the values and access the whole nested object.
Use Object.entries method:
const petList = Object.entries(fido).map(([key,value])=>{
return (
<div>{key} : {value.toString()}</div>
);
})
value.toString()
for boolean types to render correctly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With