Creating dictionary in React - javascript

I'm creating an interactive viz with React and I would like to add a slider in my viz.
import "./styles.css";
import React from "react";
import Sunburst from "react-zoomable-sunburst";
import { data } from "./data";
import { Slider } from "#mui/material";
class App extends React.Component {
onSelect(event) {
console.log(event);
}
render() {
return (
<div className="App">
<Sunburst
width="400"
height="400"
data={data.a}
count_member="size"
labelFunc={(node) => node.data.name}
_debug={false}
/>
<Slider
aria-label="Year"
defaultValue={2016}
valueLabelDisplay="auto"
step={1}
marks
min={2016}
max={2020}
/>
</div>
);
}
}
export default App;
Above is my code. I added my data from 2016 to 2020 in data.js file and I want my viz to change according to the year as I move my slider.
a: {
name: "2020",
children: [
{
name: "Campus",
children: [
{
name: "Liabilities",
children: [
{
name: "Current Liabilities",
children: [
{ name: "Accounts payable", size: 53010 },
{ name: "Accrued salaries", size: 23554 },
{ name: "Unearned revenue", size: 253322 },
{ name: "Commercial paper", size: 326008 },
{ name: "Current portion of long-term debt", size: 112431 },
{ name: "Funds held for others", size: 2500 },
{ name: "Other current liabilities", size: 71036 }
]
}
This is a part of my code in data.js and I named 2016 data as a, 2017 as b, and so on.
I wanted to name as 2016, 2017... instead of a,b... but this didn't work since data.2016 didn't work. (So I made it data.a in the code above)
So currently, my slider doesn't work. Is there any way to make dictionary or other method in React to resolve this problem?
Thanks.

use
data['2016']
That should work.

Related

select default value is not working reactjs

im triying to select by default a value into a select input but the input is not recognizing that value until i change it manually. By the default i set "All" as my default value. here is my code and the codesandbox link:
import "./styles.css";
import React, { useState, useEffect } from "react";
import { FormField } from "react-form-input-fields";
import "react-form-input-fields/dist/index.css";
export default function App() {
let [type, setType] = useState("All");
const types = [
{ label: "All", value: "All" },
{ label: "Afganistan", value: "Afganistan" },
{ label: "Albania", value: "Albania" },
{ label: "Algeria", value: "Algeria" },
{ label: "American Samoa", value: "American Samoa" },
{ label: "Andorra", value: "Andorra" },
{ label: "Angola", value: "Angola" }
];
function handletype(e) {
setType(e);
}
return (
<div className="App">
{/* <h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2> */}
<FormField
type="select"
value={type}
option={types}
label={"Select your type"}
keys={"label"}
handleOnChange={(value) => handletype(value)}
/>
</div>
);
}
link:
https://codesandbox.io/s/select-problem-ykplcm
The library you use has a bug
The source code reveals that the value prop is only checked in componendDidUpdate, but this hooks is not called for the initial render
I would rather use a different library

vue3 blocks tree does not "reload" when changing the data

I am looking for a organization chart plugin for vue 3 and I have found only this one
https://github.com/megafetis/vue3-blocks-tree
The issue that I have is when changing the ref treeData variable the chart is not loading the new structure.
I want to dynamic load the chart. When fetch the data the chart to loads the new data and display it.
Here is the codesandbox example:
https://codesandbox.io/s/flamboyant-gwen-o8vp9?file=/src/App.vue
When press the Add ... the treeData reference variable should load the new data and the chart to display it ... but it doesn't.
Any ideas ?
Should I reload the component on every fetch ?
Try to use documented way make treeData reactive.
Replace ref to reactive for treeDate definition.
Change parts of treeData on onAddData instead replacing all object.
Full changed example:
import { reactive } from "vue";
import VueBlocksTree from "vue3-blocks-tree";
import "vue3-blocks-tree/dist/vue3-blocks-tree.css";
export default {
name: "Diagram",
components: { VueBlocksTree },
setup() {
let treeData = reactive({
label: "root",
children: [
{ label: "child 1" },
{ label: "child 2" },
{
label: "subparent 1",
children: [
{ label: "subchild 1" },
{
label: "subchild 2",
children: [{ label: "subchild 11" }, { label: "subchild 22" }],
},
],
},
],
});
// let treeData = ref({});
const onAddData = () => {
Object.assign(treeData, { label: "Test", children: [{ label: "Test 1" }, { label: "Test 2" }] });
};
return {
treeData,
onAddData,
};
},
};
UPD: Change code on onAddData by adding Object.assign.

Language object prop to pass in the react component

I have created a demo using a tutorial that i have found.
This is the demo => https://codesandbox.io/s/strange-monad-otv0g?file=/src/language.js
In App.js the sidebar is receiving the array of objects as props, it all works fine
const sidebaritems = [
{
name: "first",
label: "First",
items: [
{ name: "sublink2", label: "SubLink 1" },
{ name: "sublink3", label: "SubLink 2" }
]
},
"divider",
{
name: "second",
label: "Second",
items: [
{ name: "subLink 1", label: "SubLink 1" },
{ name: "subLink 2", label: "SubLink 2" }
]
},
"divider",
{
name: "third",
label: "Third"
}
];
<SideBar items={sidebaritems} />
I want now to use an external data language file that i import where i have other translations and also sidebaritems to pass, so i have created language.js and imported in the App.js
import dataForTexts from "./language.js";
My question is, how can i pass from language.js the same sidebaritems in my sidebar component in app.js
You need a named import to import your dataForTexts . So change your import statement as
import { dataForTexts } from "./language.js";
Now pass the sidebaritems as
<SideBar items={dataForTexts.sidebaritems} />
As I understand it you need this. As items, you just need to pass your data from language.js (dataForTexts)

Issues with an object- Will not map

Whenever I run my React program, I receive the following error:
Objects are not valid as a React child (found: object with keys {mappedCats}). If you meant to render a collection of children, use an array instead.
in choicesList (at App.js:33)
What I am trying to do is take the FEATURES object, iterate through it and create a div for each category. Then iterate through the items of that category to show the name and cost of each item. I tried converting the object to an array, but it doesn't seem to be working. Originally I tried splitting this up into multiple components but I think I was overly ambitious.
The Categories component just takes the props and puts them into a div and paragraphs.
If somebody could point out my mistake I would appreciate it. Thank You
import React from 'react'
import Categories from './categories'
const choicesList = (props) => {
const FEATURES = {
Processor: [
{
name: '17th Generation Intel Core HB (7 Core with donut spare)',
cost: 700
},
{
name: 'Professor X AMD Fire Breather with sidewinder technology',
cost: 1200
}
],
"Operating System": [
{
name: 'Ubuntu Linux 16.04',
cost: 200
},
{
name: 'Bodhi Linux',
cost: 300
}
],
"Video Card": [
{
name: 'Toyota Corolla 1.5v',
cost: 1150.98
},
{
name: 'Mind mild breeze 2000',
cost: 1345
}
],
Display: [
{
name: '15.6" UHD (3840 x 2160) 60Hz Bright Lights and Knobs',
cost: 1500
},
{
name: '15.3" HGTV (3840 x 2160) Home makeover edition',
cost: 1400
},
]
};
const mappedCats = Object.keys(FEATURES).map((cat) => {
return (
<div>
<h1>{cat}</h1>
{Object.keys(FEATURES[cat]).map((item, idx) => {
return (
<Categories name={FEATURES[cat][idx].name} cost={FEATURES[cat][idx].cost}/>
)
})}
</div>
)
})
return(
{mappedCats}
)
}
export default choicesList
Because React components must render a single root element, you'd need to wrap it in either a fragment or an element:
return (
<>{ mappedCats }</>
)
As raw js (not enclosed in markup) your render method is returning an object literal:
// this is shorthand for { mappedCats: mappedCats }
return { mappedCats };
mappedCats itself is a valid element(s). Just return that
return mappedCats
const ChoicesList = (props) => {
const FEATURES = {
Processor: [
{
name: "17th Generation Intel Core HB (7 Core with donut spare)",
cost: 700,
},
{
name: "Professor X AMD Fire Breather with sidewinder technology",
cost: 1200,
},
],
"Operating System": [
{
name: "Ubuntu Linux 16.04",
cost: 200,
},
{
name: "Bodhi Linux",
cost: 300,
},
],
"Video Card": [
{
name: "Toyota Corolla 1.5v",
cost: 1150.98,
},
{
name: "Mind mild breeze 2000",
cost: 1345,
},
],
Display: [
{
name: '15.6" UHD (3840 x 2160) 60Hz Bright Lights and Knobs',
cost: 1500,
},
{
name: '15.3" HGTV (3840 x 2160) Home makeover edition',
cost: 1400,
},
],
};
const mappedCats = Object.keys(FEATURES).map((cat) => {
return (
<div>
<h1>{cat}</h1>
{Object.keys(FEATURES[cat]).map((item, idx) => {
return (
<div>
{`name: ${FEATURES[cat][idx].name}`}
<br></br>
{`cost: ${FEATURES[cat][idx].cost}`}
</div>
);
})}
</div>
);
});
return mappedCats;
//return (<div>{ mappedCats }</div>);
};
const domContainer = document.querySelector('#app');
ReactDOM.render(<ChoicesList />, domContainer);
<script crossorigin src="https://unpkg.com/react#16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.production.min.js"></script>
<div id="app"> </div>

how to set column name in mui datatables using object key

I'm trying to use an object key to set the name of a column in MUI Datatables.
I'm trying to set one of the column names with the first element of children.childName
so that in that column it will display list of child names, but only the first child.
In Current way that Im trying this, I am getting no errors, and its displaying nothing in the childName Column on the table.
How Can I access an object thats inside an array?
This is my Data:
const data = [
{
name: "Pat",
company: "Test Corp",
city: "Yonkers",
state: "NY",
children: [
{ childName: "Pat Jun", childAge: 2 },
{ childName: "Mary Jun", childAge: 2 }
]
},
];
const columns = [
{
name:name: data[0]["children"][0]["childName"],
label: "Child Name",
options: {
filter: true,
sort: true
}
}]
MuiTable.js
function MuiTable({ forms }) {
console.log("cols", columns);
return (
<MUIDataTable
title={"Title"}
data={data}
columns={columns}
options={options}
/>
);
}
By doing a console.log I can see that it is printing the value instead of the object key name
I would really appreciate any help, Thank you.
You need to use customBodyRender like this:
import React from "react";
import ReactDOM from "react-dom";
import MUIDataTable from "mui-datatables";
import { Typography } from "#material-ui/core";
import "./styles.css";
function App() {
const data = [
{
name: "Pat",
company: "Test Corp",
city: "Yonkers",
state: "NY",
children: [
{ childName: "Pat Jun", childAge: 2 },
{ childName: "Mary Jun", childAge: 2 }
]
}
];
const columns = [
{
name: "children",
label: "Child Names",
options: {
filter: true,
sort: true,
customBodyRender: (value, tableMeta, updateValue) => (
<Typography>
{value.map(child => child.childName).join(",")}
</Typography>
)
}
}
];
return (
<div>
<MUIDataTable title={"Title"} data={data} columns={columns} />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Thanks very much to #Klaus your answer. That's pretty much what I had to do, but In my case, I wanted to only display the first childName in the object children which was in an array of objects.
So I had to adapt it a bit and change my data structure as well.
This is what I ended up doing.
I first added a simple array to my data structure completely seperate to the array containing the children objects called childNames, which just came contained only the names.
This made it alot easier to access the childNames as it was just a simple array not nested in anything.
So I simply just displayed the first element in the array on Table
const columns = [
{
name: "childNames",
label: "Child Name",
options: {
filter: true,
customBodyRender: (value, tableMeta, updateValue) => {
return <div>{value[0]}</div>;
}
}
},
The reason why I created an array for just childNames, was because trying to access only just the first childName in the array containing children objects was proving very complicated and difficult.
Thanks very much for all the help.

Categories