Attempting to display globe using React.js and Cesium.js? - javascript

I've followed every guide I can find on the topic, and none of them seem to be able to help my specific problem. I can display the the Cesium app on my React webpage, but the globe, background, and thumbnails will not display, however, all of the other widgets will display (home button, time controller, etc.). If you all need more code, I will be happy to provide more :)
Here is my code:
project/src/App.js:
import React, {Component} from "react";
import Viewer from "cesium/Source/Widgets/Viewer/Viewer";
import BingMapsImageryProvider from "cesium/Source/Scene/BingMapsImageryProvider";
import CesiumTerrainProvider from "cesium/Source/Core/CesiumTerrainProvider";
const BING_MAPS_URL = "//dev.virtualearth.net";
const BING_MAPS_KEY = process.env.BING_MAPS_KEY;
const STK_TERRAIN_URL = "//assets.agi.com/stk-terrain/world";
export default class CesiumGlobe extends Component {
state = {viewerLoaded : false}
componentDidMount() {
const imageryProvider = new BingMapsImageryProvider({
url : BING_MAPS_URL,
key : BING_MAPS_KEY,
});
const terrainProvider = new CesiumTerrainProvider({
url : STK_TERRAIN_URL
});
this.viewer = new Viewer(this.cesiumContainer, {
animation : true,
baseLayerPicker : false,
fullscreenButton : false,
geocoder : false,
homeButton : true,
infoBox : false,
sceneModePicker : false,
selectionIndicator : true,
timeline : true,
navigationHelpButton : false,
scene3DOnly : true,
imageryProvider,
terrainProvider
})
}
componentWillUnmount() {
if(this.viewer) {
this.viewer.destroy();
}
}
render() {
const containerStyle = {
const containerStyle = {
width: '100%',
height: '100%',
top: 0,
left: 0,
bottom: 0,
right: 0,
position: 'fixed',
display : "flex",
alignItems : "stretch",
};
const widgetStyle = {
flexGrow : 2
}
return (
<div className="cesiumGlobeWrapper" style={containerStyle}>
<div
className="cesiumWidget"
ref={ element => this.cesiumContainer = element }
style={widgetStyle}
/>
</div>
);
}
}
Note: I generated the BingMapsApi key very recently, so this likely isn't the issue.

Related

get full Width of Labels Automatically in charts.js on Hover of DoNutChart

I am Using Charts.js Library for Displaying DoNutChart Chart.
Issue i am Facing is when i hover over the DoNutChart the label name is truncating not getting the complete width of the Labels
Js
import React from 'react';
import { Doughnut } from 'react-chartjs-2';
import { withStyles } from '#material-ui/core/styles';
import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);
const style = (theme) => ({
donut: {
backgroundColor: '',
'& canvas': { zIndex: 999 }
}
});
const DoNutChart = ({
chartData = [],//Array of Objects is received here from Parent Component
keyValue,//gets the key name which need to be mapped from Parent Component
styles = {},
labels = [],//getting the array of label names from Parent Component
classes
}) => {
let data = {
labels: [...labels],
datasets: [
{
data: chartData.map((x) => x[keyValue]),
backgroundColor: [
'#008712',
'#6C5AE0',
'#6FB1F7',
'#ED4E78',
'#FFEE80'
],
borderColor: ['#008712', '#6C5AE0', '#6FB1F7', '#ED4E78', '#FFEE80'],
borderWidth: 1
}
]
};
let options = {
maintainAspectRatio: true,
scales: {
y: {
beginAtZero: true,
display: false
}
},
plugins: {
legend: {
display: false
}
}
};
return (
// <div style={{ ...(styles || {}) }}>
<div className={classes.donut}>
<Doughnut data={data} height={100} options={options} />
</div>
);
};
export default withStyles(style)(DoNutChart);
I have tried using this reference
Changing the z index of tooltip in chartjs-2
by increasing the z-index still i am not getting the expected result
Attached image of truncated label Names need the full Label Names
enter image description here

How to export variable from react component?

I am using Mantine for a search bar and I need to get the wordcount of the text area. This is using Nodejs and React. I need to be able to export this value to use in a different file.
import React, { useState } from 'react';
import { TextInput, createStyles } from '#mantine/core';
var count = document.getElementById('count');
const useStyles = createStyles((theme, { floating }: { floating: boolean }) => ({
root: {
position: 'relative',
},
label: {
position: 'absolute',
zIndex: 2,
top: 7,
left: theme.spacing.sm,
pointerEvents: 'none',
color: floating
? theme.colorScheme === 'dark'
? theme.white
: theme.black
: theme.colorScheme === 'dark'
? theme.colors.dark[3]
: theme.colors.gray[5],
transition: 'transform 150ms ease, color 150ms ease, font-size 150ms ease',
transform: floating ? `translate(-${theme.spacing.sm}px, -28px)` : 'none',
fontSize: floating ? theme.fontSizes.xs : theme.fontSizes.sm,
fontWeight: floating ? 500 : 400,
},
required: {
transition: 'opacity 150ms ease',
opacity: floating ? 1 : 0,
},
input: {
'&::placeholder': {
transition: 'color 150ms ease',
color: !floating ? 'transparent' : undefined,
},
},
}
)
);
export function FloatingLabelInput() {
const [focused, setFocused] = useState(false);
const [value, setValue] = useState('');
const { classes } = useStyles({ floating: value.trim().length !== 0 || focused });
const uniqueid = "input";
return(
<TextInput
id={ uniqueid }
placeholder="Add anything you want to the book of the internet."
required
classNames={classes}
value={value}
onChange={(event) => setValue(event.currentTarget.value)}
onFocus={() => setFocused(true)}
onBlur={() => setFocused(false)}
mt="md"
onKeyUp={(e) => {
var text = value.split(' ');
var wordcount = 0;
for (var i = 0; i < text.length; i++) {
if (text[i] !== ' ') {
wordcount++;
}
}
count.innerText = wordcount;
}
}
autoComplete="nope"
/>
);
}
As you can see, it correctly outputs it into html, but returning inside the function doesnt work at all.
I tried exporting it, I tried returning it to the function but it doesn't see it. I tried exporting and using modules exports but that doesnt work either. Any help would be appreciated.
In the following code snippet, my root component (called App) is responsible for keeping the app state, but it can give any piece of state to any of its children. It can also give state modifiers (setX functions) to its children, which is what I am demonstrating here:
function Input ({ setWordCount }) {
function updateWordCount (event) {
setWordCount(event.target.value.split(' ').length)
}
return <input type="text" onKeyUp={updateWordCount} />
}
function SomeOtherComponent ({ count }) {
return (
<span>: {count} words</span>
)
}
function App () {
const [wordCount, setWordCount] = React.useState(0)
return (
<p>
<Input setWordCount={setWordCount} />
<SomeOtherComponent count={wordCount} />
</p>
)
}
ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.5/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.5/umd/react-dom.production.min.js"></script>
<div id="app" />
As you can see, the Input component can call the setWordCount function provided by its parent to change a piece of state. Then, the parent (App) can give that piece of state to any number of its children. Each component can live in a separate file too, this would still work…
I'm not sure if I understood your question correctly, but hopefully, this can give you ideas you can reuse in your own code?

TypeError: this.querySelectorAll is not a function while using D3Funnel in react js

I am using d3funnel in my react application (which is based on typescript) and I keep getting the error of TypeError: this.querySelectorAll is not a function. And, I don't understand why it is happening. Here is a sample code of mine:
import * as React from 'react'
import * as D3Funnel from 'd3-funnel'
import * as d3 from "d3";
const FunnelChart: React.FC = () => {
const Ref = React.useRef(null)
var data = [
['Applicants', 267 , '#1e4684', '#1e4684'],
['Interviews', 134, '#1e4684'],
['Assessments', 48, '#1e4684'],
['Hired',26, '#1e4684']
];
var options = {
width : 200,
height : 400,
bottomWidth : 1/2,
bottomPinch : 0, // How many sections to pinch
isCurved : true, // Whether the funnel is curved
curveHeight : 10, // The curvature amount
fillType : "gradient", // Either "solid" or "gradient"
isInverted : false, // Whether the funnel is inverted
hoverEffects : true, // Whether the funnel has effects on hover
fontSize : '18px'
};
React.useEffect(() => {
var funnel = new D3Funnel( data, options );
funnel.draw (d3.select(Ref.current));
}, [])
return (
<>
<div ref = {Ref}>
</div>
</>
)
} `
I really appreciate any help.
Edit: Here is the error:
react-dom.development.min.js:1 Uncaught TypeError: this.querySelectorAll is not a function at Array.__webpack_exports__.default (d3-funnel.js?f3d7:2417) at Selection.eval [as selectAll] (d3-funnel.js?f3d7:2395) at D3Funnel.destroy (d3-funnel.js?f3d7:194) at D3Funnel.draw (d3-funnel.js?f3d7:217) at eval (index.tsx?21e5:57) at Sg (react-dom.development.min.js:1) at Eg (react-dom.development.min.js:1) at HTMLUnknownElement.e (react-dom.development.min.js:1) at at g (react-dom.development.min.js:1)
you need to pass ref.current to D3Funnel while initializing it and data & option as parameter of draw function.
Here's the solution
import React, { useRef, useEffect } from "react";
import D3Funnel from "d3-funnel";
export default function App() {
const chartRef = useRef(null);
var data = [
{ label: "Teal", value: 12000, backgroundColor: "#008080" },
{ label: "Byzantium", value: 4000, backgroundColor: "#702963" },
{ label: "Persimmon", value: 2500, backgroundColor: "#ff634d" },
{ label: "Azure", value: 1500, backgroundColor: "#007fff" }
];
var options = {
width: 200,
height: 400,
bottomWidth: 1 / 2,
bottomPinch: 2, // How many sections to pinch
isCurved: true, // Whether the funnel is curved
curveHeight: 10, // The curvature amount
fillType: "gradient", // Either "solid" or "gradient"
isInverted: true, // Whether the funnel is inverted
hoverEffects: true, // Whether the funnel has effects on hover
fontSize: "18px",
label: {
format: "{l}\n{f}"
}
};
useEffect(() => {
const chart = new D3Funnel(chartRef.current);
console.log(chart);
chart.draw(data, options);
}, []);
return <div className="App" ref={chartRef}></div>;
}

How to make chat like UI with chat bubbles in React JS

I have some JSON data in dummyData. I am not sure how can I place the chat bubbles on left and right according to the direction. I am using Material UI and context API. Image for the reference. I don't want to use any library other than material UI.
Currently, every chat bubble is positioned to the left. How to position bubbles according to the direction. Code so far (CodeSandbox):
import React from 'react';
import makeStyles from '#material-ui/core/styles/makeStyles';
const useStyles = makeStyles(theme => ({
container: {
bottom: 0,
position: 'fixed'
},
bubbleContainer: {
width: '100%'
},
bubble: {
border: '0.5px solid black',
borderRadius: '10px',
margin: '5px',
padding: '10px',
display: 'inline-block'
}
}));
const ChatLayout = () => {
const classes = useStyles();
const dummyData = [
{
message: '1: This should be in left',
direction: 'left'
},
{
message: '2: This should be in right',
direction: 'right'
},
{
message: '3: This should be in left again',
direction: 'left'
}
];
const chatBubbles = dummyData.map((obj, i = 0) => (
<div className={classes.bubbleContainer}>
<div key={i++} className={classes.bubble}>
<div className={classes.button}>{obj.message}</div>
</div>
</div>
));
return <div className={classes.container}>{chatBubbles}</div>;
};
export default ChatLayout;
You can create separate div of chat bubble and apply CSS. And where you are receiving messages append the bubble div to your user list.

Dynamic components: Calling element by ref

One part of my application is an image gallery. When the user clicks on an image, I want to put an opaque layer over the image to visualize that it is selected.
When I display the layer, and I click on the image to deselect it, naturally I'm actually clicking on the layer.
Here's the relevant ReactJS code to show what I mean:
{images.map((i, idx) => (
<div key={"cont"+idx} className="container">
<img src={i.images} ref={"img"+idx} />
<div onClick={this.handleIconDeselect} id={"div_"+idx}></div>
</div>
)
)}
I tried to give the img a unique ref (as shown above), but I'm having trouble selecting the correct img.
This is how I try to select the correct image:
handleIconDeselect = (event) => {
var imgref = "icon"+event.target.id.split("_").pop();
this.refs.imgref.click();
}
However, I get the following error message:
TypeError: Cannot read property 'click' of undefined
How can I select the correct image while using unique refs?
Alternatively, if the way I'm trying to achieve this is bad practice (I know you should only use refs when absolutely necessary), what is a better way to do it?
Try use state as here: https://codesandbox.io/s/m4276x643y
Maybe that is not the best way but it give you an rough idea.
import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
const coverStyle = {
position: "fixed",
top: 0,
left: 0,
zIndex: -1,
opacity: 0,
width: "100%",
height: "100%",
background: "#000"
};
const coverStyleShow = {
...coverStyle,
zIndex: 1,
opacity: 1
};
const imgShow = {
zIndex: 10,
position: "relative"
};
const images = [
"https://dummyimage.com/100.png/f10/fff",
"https://dummyimage.com/100.png/f20/fff",
"https://dummyimage.com/100.png/f30/fff",
"https://dummyimage.com/100.png/f40/fff",
"https://dummyimage.com/100.png/f50/fff",
"https://dummyimage.com/100.png/f60/fff",
"https://dummyimage.com/100.png/f70/fff"
];
class App extends Component {
constructor(props) {
super(props);
this.state = {
cover: coverStyle,
img: imgShow,
imgId: null,
imgShow: false
};
}
handleImageClick = (target, idx) => {
// you can do something with this "target"...
this.setState({
cover: coverStyle,
coverShow: coverStyleShow,
imgId: idx,
imgShow: !this.state.imgShow
});
};
render() {
return (
<div>
<Hello name="CodeSandbox" />
<h2>Start editing to see some magic happen {"\u2728"}</h2>
<div>
{images.map((img, idx) => (
<img
key={img}
src={img}
style={idx === this.state.imgId ? this.state.img : null}
onClick={event => this.handleImageClick(event.target, idx)}
alt="dummy img"
/>
))}
</div>
<span
style={this.state.imgShow ? this.state.coverShow : this.state.cover}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));

Categories

Resources