I thought this would be a simple task, but I've been working on this all day but still can't seem to figure it out.
I am receiving a very large (multiple layers of objects) JSON file which I stored in a state of my component, now I need to render that data on the screen. This has become difficult, because within the object I have several others objects which also may contain other objects.
So far, I am using Object.keys(myJSONObject).map(...) to try to get it done, however I can't seem to find a way to reach all the 'sub-objects'. Here is my current code:
render: function(){
return (
<div>
{
Object.keys(_this.state.content).map(function (key) {
if (typeof _this.state.content[key] instanceof Object){
//go through all objects and sub-objects???
}
return <div > Key: {
key
}, Value: {
_this.state.content[key]
} </div>;
})
}
</div>
);
}
Edit: I should probably add that my object is _this.state.content
Edit 2: Here is an example of the object I am looking to iterate through. Keep in mind that is it a lot bigger than this.
{ "3.8": [ "Something something" ],
"3.2": [ { "Blabla": [ "More things I am saying", "Blablablabal", "Whatever" ] } ],
"2.9": [ { "Foo": [ "bar", "something something something something", "blablablabalbalbal" ] } ]}
Edit 3: Here is how I would somewhat like it to look when rendered:
3.8:
- Something something
3.2:
- Blabla:
- More things I am saying
- Blablablabal
- Whatever
2.9:
-Foo:
-bar
...
Is this what your are after: http://codepen.io/PiotrBerebecki/pen/PGjVxW
The solution relies on using React's reusable components. It accepts objects of varying levels of nesting as per your example. You can adjust it further to accommodate even more types of objects.
const stateObject = {
"3.8": [ "Something something" ],
"3.2": [ { "Blabla": [ "More things I am saying", "Blablablabal", "Whatever" ] } ],
"2.9": [ { "Foo": [ "bar", "something something something something", "blablablabalbalbal" ] } ]
}
class App extends React.Component {
render() {
const renderMainKeys = Object.keys(stateObject)
.map(mainKey => <MainKey mainKey={mainKey}
innerObject={stateObject[mainKey]} />);
return (
<div>
{renderMainKeys}
</div>
);
}
}
class MainKey extends React.Component {
render() {
if (typeof this.props.innerObject[0] === 'string') {
return (
<div>
<h4>{this.props.mainKey}</h4>
<ul>
<li>{this.props.innerObject[0]}</li>
</ul>
</div>
);
}
const innerObjectKey = Object.keys(this.props.innerObject[0])[0];
const innerList = this.props.innerObject[0][innerObjectKey];
return (
<div key={this.props.mainKey}>
<h4>{this.props.mainKey}</h4>
<InnerKey innerObjectKey={innerObjectKey} innerList={innerList}/>
</div>
)
}
}
class InnerKey extends React.Component {
render() {
return (
<ul>
<li>{this.props.innerObjectKey}</li>
<InnerList innerList={this.props.innerList} />
</ul>
)
}
}
class InnerList extends React.Component {
render() {
if (!Array.isArray(this.props.innerList)) {
return (
<ul>
<li>{this.props.innerList}</li>
</ul>
);
}
const listItems = this.props.innerList.map(function(item, index) {
return <li key={index}>{item}</li>;
});
return (
<ul>
{listItems}
</ul>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
Here is a code which I wrote sometime back to handle 3 layers of nesting in my json file.
JSON
var a = {
"parent":{
"name":"x",
"child":{
"name":"y",
"subchild":{
"name":"check"
}
}
}
}
Iterator
Object.keys(obj).map(function(key,index){
let section = obj[key]
//getting subsections for a single section
let subSections = section["subsections"] // get you nested object here
Object.keys(subSections).map(function(subSectionId,key){
//getting a single sub section
let subSection=subSections[subSectionId]
//getting instruments for a sub section
let nestedSection = subSection["//key"] //get you next nested object here
Object.keys(instruments).map(function(instrumentId,key){
//operation
}
})
})
})
})
Hope it helps.
Related
The function is getting the value of a button click as props. Data is mapped through to compare that button value to a key in the Data JSON called 'classes'. I am getting all the data correctly. All my console.logs are returning correct values. But for some reason, I cannot render anything.
I've tried to add two return statements. It is not even rendering the p tag with the word 'TEST'. Am I missing something? I have included a Code Sandbox: https://codesandbox.io/s/react-example-8xxih
When I click on the Math button, for example, I want to show the two teachers who teach Math as two bubbles below the buttons.
All the data is loading. Just having an issue with rendering it.
function ShowBubbles(props){
console.log('VALUE', props.target.value)
return (
<div id='bubbles-container'>
<p>TEST</p>
{Data.map((item,index) =>{
if(props.target.value == (Data[index].classes)){
return (
<Bubble key={index} nodeName={Data[index].name}>{Data[index].name}
</Bubble>
)
}
})}
</div>
)
}
Sandbox Link: https://codesandbox.io/embed/react-example-m1880
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
const circleStyle = {
width: 100,
height: 100,
borderRadius: 50,
fontSize: 30,
color: "blue"
};
const Data = [
{
classes: ["Math"],
name: "Mr.Rockow",
id: "135"
},
{
classes: ["English"],
name: "Mrs.Nicastro",
id: "358"
},
{
classes: ["Chemistry"],
name: "Mr.Bloomberg",
id: "405"
},
{
classes: ["Math"],
name: "Mr.Jennings",
id: "293"
}
];
const Bubble = item => {
let {name} = item.children.singleItem;
return (
<div style={circleStyle} onClick={()=>{console.log(name)}}>
<p>{item.children.singleItem.name}</p>
</div>
);
};
function ShowBubbles(props) {
var final = [];
Data.map((item, index) => {
if (props.target.value == Data[index].classes) {
final.push(Data[index])
}
})
return final;
}
function DisplayBubbles(singleItem) {
return <Bubble>{singleItem}</Bubble>
}
class Sidebar extends Component {
constructor(props) {
super(props);
this.state = {
json: [],
classesArray: [],
displayBubble: true
};
this.showNode = this.showNode.bind(this);
}
componentDidMount() {
const newArray = [];
Data.map((item, index) => {
let classPlaceholder = Data[index].classes.toString();
if (newArray.indexOf(classPlaceholder) == -1) {
newArray.push(classPlaceholder);
}
// console.log('newArray', newArray)
});
this.setState({
json: Data,
classesArray: newArray
});
}
showNode(props) {
this.setState({
displayBubble: true
});
if (this.state.displayBubble === true) {
var output = ShowBubbles(props);
this.setState({output})
}
}
render() {
return (
<div>
{/* {this.state.displayBubble ? <ShowBubbles/> : ''} */}
<div id="sidebar-container">
<h1 className="sidebar-title">Classes At School</h1>
<h3>Classes To Search</h3>
{this.state.classesArray.map((item, index) => {
return (
<button
onClick={this.showNode}
className="btn-sidebar"
key={index}
value={this.state.classesArray[index]}
>
{this.state.classesArray[index]}
</button>
);
})}
</div>
{this.state.output && this.state.output.map(item=><DisplayBubbles singleItem={item}/>)}
</div>
);
}
}
ReactDOM.render(<Sidebar />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
The issue here is ShowBubbles is not being rendered into the DOM, instead (according the sandbox), ShowBubbles (a React component) is being directly called in onClick button handlers. While you can technically do this, calling a component from a function will result in JSX, essentially, and you would need to manually insert this into the DOM.
Taking this approach is not very React-y, and there is usually a simpler way to approach this. One such approach would be to call the ShowBubbles directly from another React component, e.g. after your buttons using something like:
<ShowBubbles property1={prop1Value} <etc...> />
There are some other issues with the code (at least from the sandbox) that you will need to work out, but this will at least help get you moving in the right direction.
How can i push html into the last array. I was trying to add an item and supposed be add instantly into list array. The cod is working except I'm struggling to add new list into last array.
function addItem(id,name){
const array = JSON.parse(localStorage.getItem('categories'));
array.push({
name: name,
id:id,
});
//<li>{name}</li> push this into last array
localStorage.setItem('categories',JSON.stringify(array));
}
{categories.map(function(item, key){
return <div>
<ul>
<li>item.name</li>
</ul>
<button onClick={() => addItem(item.id,'value name')}>Add</button>
</div>
})}
Something looks wrong in your example. I have added a complete exampl. You can maintain localStorage and State both. I hope this example helps you.
You mistake is that while adding new item you are pushing it to localStoage due to which react dom does not get rerendered. You have to update the value of state for that.
class App extends React.Component {
constructor() {
super();
this.state = {
categories: [
{
name: "Hello",
id: 1
},
{
name: "World",
id: 2
}
]
};
this.addItem = this.addItem.bind(this);
this.SaveToLocalStorage = this.SaveToLocalStorage.bind(this);
}
SaveToLocalStorage() {
const categories = this.state.categories;
localStorage.setItem("categories", JSON.stringify(categories));
}
addItem(id, name) {
const categories = this.state.categories;
categories.push({
name: name,
id: id
});
this.setState({ categories });
//localStorage.setItem("categories", JSON.stringify(categories));
}
render() {
let categories = this.state.categories;
const test = categories.map(item => (
<div key={item.id}>
<li>{item.name}</li>
</div>
));
return (
<div>
{test}
<button onClick={() => this.addItem(Date.now(), "Item")}>
Click to Add More
</button>
<button onClick={() => this.SaveToLocalStorage()}>
Save To LocalStorage{" "}
</button>
</div>
);
}
}
ReactDOM.render( < App / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I guess this is what you are asking for. You just need to set it to state and re-render it when ever you are trying to add an element to list/array. I don't know why you are setting it to local storage but you can do it from state directly if your intention is to just store the previous array for future additions.
import React, { Component } from "react";
class App extends Component {
state = {};
constructor(props){
super(props);
this.state={
arr = []
}
}
addItem(id, name) {
const array = JSON.parse(localStorage.getItem("categories"));
array.push({
name: name,
id: id
});
//<li>{name}</li> push this into last array
localStorage.setItem("categories", JSON.stringify(array));
this.setState({arr:array});
}
renderList = () => {
return this.state.array.map(function(item, key) {
return (
<div>
<ul>
<li>item.name</li>
</ul>
<button onClick={() => addItem(item.id, "value name")}>Add</button>
</div>
);
});
};
render() {
return <div>{this.renderList()}</div>;
}
}
export default App;
So I am learning React, and I've tried searching for solutions to my problem both on stackoverflow and on React's own documentation, but I am still stumped.
Essentially, I have a list of 10 subreddits that is being mapped to list items in the form of the subredditsArray variable.
I render the results, and try to pass the selected item when I click that list item to my getSubredditInfo function. However, this doesn't work - event.target.key is undefined. (To clarify, I am looking to grab the key of the single list element that I have clicked).
When I try to just get event.target, I get the actual htmlElement (ex: <li>Dota2</li>), where as I want to get the key, or at least this value into a string somehow without the tags. I also tried putting my onClick method in the list tag of the map function, but that did not work.
Here is the relevant code:
//this is where I get my data
componentDidMount(){
fetch('https://www.reddit.com/api/search_reddit_names.json?query=dota2')
.then(results => {
return results.json();
})
.then(redditNames => {
//this is there I set my subreddits state variable to the array of strings
this.setState({subreddits: redditNames.names});
})
}
getSubredditInfo(event){
//console.log(event.target.key); <-- DOESNT WORK
}
render() {
var subredditsArray = this.state.subreddits.map(function(subreddit){
return (<li key={subreddit.toString()}>{subreddit}</li>);
});
return (
<div className="redditResults">
<h1>Top 10 subreddits for that topic</h1>
<ul onClick={this.getSubredditInfo}>{subredditsArray}</ul>
</div>
);
}
My questions essentially boil down to:
How do I grab the key value from my list object?
Additionally, is there a better way to generate the list than I currently am?
Thank you in advance.
EDIT: Added my componentDidMount function in hopes it clarifies things a bit more.
try the following code:
class App extends React.Component {
constructor(props){
super(props);
this.state = {subreddits:[]};
}
componentDidMount(){
fetch('https://www.reddit.com/api/search_reddit_names.json?query=dota2')
.then(results => {
return results.json();
})
.then(redditNames => {
//this is there I set my subreddits state variable to the array of strings
this.setState({subreddits: redditNames.names});
})
}
getSubredditInfo(subreddit){
console.log(subreddit);
}
render() {
return <div className="redditResults">
<h1>Top 10 subreddits for that topic</h1>
<ul>
{
this.state.subreddits.map((subreddit)=>{
return (<li key={subreddit.toString()} onClick={()=>this.getSubredditInfo(subreddit)}>{subreddit}</li>);
})
}
</ul>
</div>;
}
}
ReactDOM.render(
<App/>,
document.getElementById('container')
);
<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="container">
<!-- This element's contents will be replaced with your component. -->
</div>
please check the onClick event handler now. its an arrow function and its calling the getSubredditInfo function with your subreddit now. so you will get it there.
so its basically different way of calling the handler to pass data to the handler.
it works as you expect it to.
You can use lamda function or make component for item list which have own value for getSubredditInfo function
getSubredditInfo(value) {}
render() {
var subredditsArray = this.state
.subreddits.map((subreddit, i) =>
(<li key={i}
onClick={() => this.getSubredditInfo(subreddit)}>{subreddit}</li>));
return (
<div className="redditResults">
<h1>Top 10 subreddits for that topic</h1>
<ul>{subredditsArray}</ul>
</div>
);
}
1) Key should be grabbed either by the id in your object in array. Or you can combine the 2 properties to create a unique key for react to handle re-renders in a better way.
If you have a string array, you may use a combination of string value + index to create a unique value, although using index is not encouraged.
Given a quick example for both below.
2) A better way could be to move your map function into another function and call that function in render function, which will return the required JSX. It will clean your render function.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
subredditsObjArray: [
{ id: 1, value: 'A'},
{ id: 2, value: 'B'},
{ id: 3, value: 'C'},
{ id: 4, value: 'D'}
],
subredditsArray: ['A', 'B', 'C', 'D'],
selectedValue: ''
};
}
getSubredditInfo = (subreddit) => {
console.log(subreddit)
this.setState({
selectedValue: ((subreddit && subreddit.id) ? subreddit.value : subreddit),
});
}
render() {
return (
<div className="redditResults">
<p>Selected Value: {this.state.selectedValue}</p>
<h1>Top {this.state.subredditsArray.length || '0'} subreddits for that topic</h1>
<p>With Objects Array</p>
<ul>
{
this.state.subredditsObjArray
&& this.state.subredditsObjArray.map(redditObj => {
return (<li key={redditObj.id}><button onClick={() => this.getSubredditInfo(redditObj)}>{redditObj.value || 'Not Found'}</button></li>);
})
}
</ul>
<br />
<p>With Strings Array</p>
<ul>
{
this.state.subredditsArray
&& this.state.subredditsArray.map((reddit, index) => {
return (<li key={reddit + '-' + index}><button onClick={() => this.getSubredditInfo(reddit)}>{reddit || 'Not Found'}</button></li>);
})
}
</ul>
</div>
);
}
}
ReactDOM.render(
<App etext="Edit" stext="Save" />,
document.getElementById('container')
);
<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="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Are you trying to do this? I'm not sure what you want to do.
getSubredditInfo(e, subreddit) {
console.log(subreddit)
}
render() {
const { subreddits } = this.state
var subredditsArray = subreddits.map(subreddit => (
<li
key={subreddit.toString()}
onClick={(e) => {
this.getSubredditInfo(e, subreddit)
}}
>
{subreddit}
</li>
))
return (
<div className="redditResults">
<h1>Top 10 subreddits for that topic</h1>
<ul>{subredditsArray}</ul>
</div>
);
}
The key purpose is to pass your subreddit to the onClick function so you will receive the value while you click the item.
If you still get error try this and tell me what's happened.
render() {
const { subreddits } = this.state
var subredditsArray = subreddits.map(subreddit => (
<li
key={subreddit.toString()}
onClick={(e) => {
console.log(subreddit.toString())
}}
>
{subreddit}
</li>
))
return (
<div className="redditResults">
<h1>Top 10 subreddits for that topic</h1>
<ul>{subredditsArray}</ul>
</div>
);
}
I am new to react.
this.state = { histories: [
{
"qas":[
{"question": "hi1", "answer": "hello1"},
{"question": "hi2", "answer": "hello2"}
]
}
] };
render(){
return (
<div>
<History
histories={this.state.histories} />
</div>
);
}
In separate component page, I would like to use react js to render question and answer by loop or map, however I tried map, it didn't recognize map. I have tried for loop, but it didn't get the child attribute from it.
const history = ({histories}) => {
return(
<div>
{histories[0].qas[0].question}
</div>
<div}>
{histories[0].qas[0].answer}
</div>
);
}
Here is an example with map, hope it will help.
const History = ({histories}) => {
// Quick, hacky way to set key.
// More on keys in React https://facebook.github.io/react/docs/lists-and-keys.html#keys
let key = 1;
const questionsAndAnswers = histories[0].qas.map(child =>
<div key={key++}>
<div>{child.question}</div>
<div>{child.answer}</div>
</div>
);
return (
<div>{questionsAndAnswers}</div>
);
};
class Histories extends React.Component {
constructor(props) {
super(props);
this.state = {
histories: [
{
"qas":[
{"question": "hi1", "answer": "hello1"},
{"question": "hi2", "answer": "hello2"}
]
}
]
};
}
render() {
return(
<div>
<History histories={this.state.histories}/>
</div>
)
}
}
ReactDOM.render(
<Histories/>,
document.getElementById("history")
);
<div id="history"></div>
<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>
If you remove the “div” from the <div>{questionsAndAnswers}</div>, then you’ll get the error you encountered “A valid React element (or null)…”. If you want to render multiple elements you need to wrap them in a div. More on this https://facebook.github.io/react/docs/jsx-in-depth.html#jsx-children
It does not recognize this histories, because I bet they are undefined at your start.
const history = ({histories}) => {
if (!histories || histories.length < 1) return (<div>nothing</div>);
return histories.map(v => (<div>JSON.stringify(v)</div>))
}
Another problem could be this.state.roundshistories. It is undefined in your example.
I would like to use universe:i18n for translating my meteor application (using react).
In this component you can see, that I iterate through an array using map() and as the output I would like to get the categories as translations:
imports/ui/components/example.jsx
import React, { Component } from 'react'
import i18n from 'meteor/universe:i18n'
class Example extends Component {
getCategories(index) {
const categories = [ 'one', 'two', 'three' ]; // <-- Get correct translations of these elements
return categories[index - 1];
}
render() {
return (
<div id="content">
{ this.props.sections.map((i) => {
return (
<div>
{ this.getCategories(i.index) }
</div>
);
}) }
</div>
);
}
}
i18n/de.i18.json
{
categories: {
one: 'Eins',
two: 'Zwei',
three: 'Drei'
}
}
I tried to do it with
const T = i18n.createComponent()
class Example extends Component {
getCategories(index) {
const categories = [ 'one', 'two', 'three' ]; // <-- Get correct translations of these elements
return categories[index - 1];
}
render() {
return (
<div id="content">
{ this.props.sections.map((i) => {
return (
<div>
<T>categories[{ this.getCategories(i.index) }]</T>
</div>
);
}) }
</div>
);
}
}
It won't work, because you have to use dot instead of bracker notation, so
<T>categories.{ this.getCategories(i.index) }</T>
Instead of
<T>categories[{ this.getCategories(i.index) }]</T>
But it still won't work, because it will create an children array, but only string is accepted, so use it like this:
<T children={`categories.${ this.getCategories(i.index) }`} />
Source.