How can I output both the key and value of my state?
How can I output both the key and value of my state?
I want to be able to output both the key and the value of the key of items in my state. I tried using [this.state[field]] but that didn't work either.
[this.state[field]]
Example:
https://jsfiddle.net/n5u2wwjg/164470/
class App extends React.Component
constructor(props)
super(props)
this.state =
type: 'valueOfType',
subType: 'valueOfSubType',
anotherThing: 'valueOfOther'
renderItem = (field) =>
return <div>['nameOfKey']: field</div>
render()
const type, subType, anotherThing = this.state;
return (
<div>
<p><strong>Actual output:</strong></p>
this.renderItem(type)
this.renderItem(subType)
this.renderItem(anotherThing)
<hr/>
<p><strong>Desired output:</strong></p>
<div>type: valueOfType</div>
<div>subType: valueOfSubType</div>
<div>anotherThing: valueOfOther</div>
</div>
)
this.state[field]
renderItem
1 Answer
1
As @Li357 suggested you can pass the key as a string and use it like this.state[field] in your method. Alternatively, you can use Object.entries and map to render all the fields.
this.state[field]
Object.entries
map
class App extends React.Component
constructor(props)
super(props)
this.state =
type: 'valueOfType',
subType: 'valueOfSubType',
anotherThing: 'valueOfOther'
renderItem = (field) =>
return <div>field: this.state[field]</div>
renderAll = () => Object.entries( this.state ).map( ([key,value]) =>
<p>key:value</p>
);
render()
return (
<div>
<p><strong>Actual output:</strong></p>
this.renderItem("type")
this.renderItem("subType")
this.renderItem("anotherThing")
<hr />
this.renderAll()
<hr />
<p><strong>Desired output:</strong></p>
<div>type: valueOfType</div>
<div>subType: valueOfSubType</div>
<div>anotherThing: valueOfOther</div>
</div>
)
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Pass the key as a string. Then do
this.state[field]inrenderItemto get the value associated with that key.– Li357
Sep 3 at 23:12