when im trying to import the code via sandbox or trying to modify the github repo code its giving me (NextJS)
im not used to typescript btw and when im directly importing code from codesandbox its showing me no tags since its not dynamically imported as required in NEXTJS
heres the error
'Cannot read properties of undefined (reading 'forEach')' error
heres the code btw ( og github link for reference : https://github.com/teaguestockwell/react-icon-cloud )
import allIcons from "simple-icons";
import { v4 } from "uuid";
import {
Cloud,
renderSimpleIcon,
fetchSimpleIcons,
SimpleIcon,
} from "react-icon-cloud";
const Componente = () => {
const tagCanvasOptions = {
clickToFront: 500,
// decel: number
depth: 1,
imageScale: 2,
initial: [0.1, -0.1],
outlineColour: "#0000",
reverse: true,
tooltip: "native", // null | 'div'
// tooltipClass: string
tooltipDelay: 0,
wheelZoom: false,
};
const slugs = [
"typescript",
"javascript",
"dart",
"java",
"react",
"flutter",
"android",
"html5",
"css3",
"nodedotjs",
"express",
"nextdotjs",
"prisma",
"amazonaws",
"postgresql",
"firebase",
"nginx",
"vercel",
"testinglibrary",
"jest",
"cypress",
"docker",
"git",
"jira",
"github",
"gitlab",
"visualstudiocode",
"androidstudio",
"sonarqube",
"figma",
];
const useIcons = (slugs) => {
const [icons, setIcons] = React.useState();
React.useEffect(() => {
fetchSimpleIcons(slugs).then(setIcons);
}, []);
if (icons) {
return Object.values(icons.simpleIcons).map((icon) =>
renderSimpleIcon({
icon,
size: 42,
aProps: {
onClick: (e) => e.preventDefault(),
},
})
);
}
return <a>Loading</a>;
};
const icons = useIcons(slugs);
return (
<div>
<Cloud>{icons}</Cloud>
</div>
);
};
export default Componente;
Related
I am dynamically changing the values that are displayed on the areachart. But for some reason the chart is only displayed if I change one of the dynamic variable with a hard coded number in the array. For example
const data = [
["Year", "Free Cash Flow", "Revenue"],
[this.props.date1, this.props.cashFlow1, this.props.revenue1],
[this.props.date2, this.props.cashFlow2, this.props.revenue2],
[this.props.date3, this.props.cashFlow3, this.props.revenue3],
[this.props.date4, this.props.cashFlow4, this.props.revenue4],
[this.props.date5, this.props.cashFlow5, this.props.revenue5],
];
that is how I structured my data array, but it doesn't renders and give the following error All series on a given axis must be of the same data type. However, if I replace this.props.revenue1 with let say 100 the area chart renders
const data = [
["Year", "Free Cash Flow", "Revenue"],
[this.props.date1, this.props.cashFlow1, 100],
[this.props.date2, this.props.cashFlow2, this.props.revenue2],
[this.props.date3, this.props.cashFlow3, this.props.revenue3],
[this.props.date4, this.props.cashFlow4, this.props.revenue4],
[this.props.date5, this.props.cashFlow5, this.props.revenue5],
];
I have looked at other examples and I can't seem to find a mistake I could've made.
import React, {Component} from "react";
import { Chart } from "react-google-charts";
class AreaChart extends Component {
render () {
const chartEvents = [
{
callback: ({ chartWrapper, google }) => {
const chart = chartWrapper.getChart();
chart.container.addEventListener("click", (ev) => console.log(ev))
},
eventName: "ready"
}
];
const rev1 = this.props.revenue1;
const FCF1 = this.props.cashFlow1;
const data = [
["Year", "Free Cash Flow", "Revenue"],
[this.props.date1, this.props.cashFlow1, this.props.revenue1],
[this.props.date2, this.props.cashFlow2, this.props.revenue2],
[this.props.date3, this.props.cashFlow3, this.props.revenue3],
[this.props.date4, this.props.cashFlow4, this.props.revenue4],
[this.props.date5, this.props.cashFlow5, this.props.revenue5],
];
const options = {
isStacked: true,
height: 300,
legend: { position: "top", maxLines: 3 },
vAxis: { minValue: 0 },
};
return (
<Chart
chartType="AreaChart"
width="75%"
height="400px"
data={data}
options={options}
chartEvents={chartEvents}
/>
);
}
}
export default AreaChart;
I've implemented the TradingView charting library on my react project following the documentation provided.
Copy charting_library folder from
https://github.com/tradingview/charting_library/ to /public and to
/src folders. Copy datafeeds folder from
https://github.com/tradingview/charting_library/ to /public.
exactly as mentioned in the documentation , when i run yarn start it's working and showing however , when I build and try to serve it using nginx .
I get an error saying .
TypeError: Cannot read properties of undefined (reading
'UDFCompatibleDatafeed').
import * as React from "react";
import "./index.css";
import {
widget,
ChartingLibraryWidgetOptions,
IChartingLibraryWidget
} from "../../../charting_library";
import { useMarket, USE_MARKETS } from "../../utils/markets";
import * as saveLoadAdapter from "./saveLoadAdapter";
import { flatten } from "../../utils/utils";
import { BONFIDA_DATA_FEED } from "../../utils/bonfidaConnector";
import {} from "../../../charting_library";
export interface ChartContainerProps {
symbol: ChartingLibraryWidgetOptions["symbol"];
interval: ChartingLibraryWidgetOptions["interval"];
auto_save_delay: ChartingLibraryWidgetOptions["auto_save_delay"];
// BEWARE: no trailing slash is expected in feed URL
// datafeed: any;
datafeedUrl: string;
libraryPath: ChartingLibraryWidgetOptions["library_path"];
chartsStorageUrl: ChartingLibraryWidgetOptions["charts_storage_url"];
chartsStorageApiVersion: ChartingLibraryWidgetOptions["charts_storage_api_version"];
clientId: ChartingLibraryWidgetOptions["client_id"];
userId: ChartingLibraryWidgetOptions["user_id"];
fullscreen: ChartingLibraryWidgetOptions["fullscreen"];
autosize: ChartingLibraryWidgetOptions["autosize"];
studiesOverrides: ChartingLibraryWidgetOptions["studies_overrides"];
containerId: ChartingLibraryWidgetOptions["container_id"];
theme: string;
}
export interface ChartContainerState {}
export const TVChartContainer = () => {
// let datafeed = useTvDataFeed();
const defaultProps: ChartContainerProps = {
symbol: "BTC/USDC",
// #ts-ignore
interval: "60",
auto_save_delay: 5,
theme: "Dark",
containerId: "tv_chart_container",
// datafeed: datafeed,
libraryPath: "/charting_library/",
chartsStorageApiVersion: "1.1",
clientId: "tradingview.com",
userId: "public_user_id",
fullscreen: false,
autosize: true,
datafeedUrl: BONFIDA_DATA_FEED,
studiesOverrides: {}
};
const tvWidgetRef = React.useRef<IChartingLibraryWidget | null>(null);
const { market } = useMarket();
const chartProperties = JSON.parse(
localStorage.getItem("chartproperties") || "{}"
);
React.useEffect(() => {
const savedProperties = flatten(chartProperties, {
restrictTo: ["scalesProperties", "paneProperties", "tradingProperties"]
});
let newWindow :any = window ;
console.log("defaultProps.datafeedUrl", newWindow.Datafeeds);
const widgetOptions: ChartingLibraryWidgetOptions = {
symbol:
USE_MARKETS.find(
(m) => m.address.toBase58() === market?.publicKey.toBase58()
)?.name || "SRM/USDC",
// BEWARE: no trailing slash is expected in feed URL
// tslint:disable-next-line:no-any
// #ts-ignore
// datafeed: datafeed,
// #ts-ignore
datafeed:new (window as any).Datafeeds.UDFCompatibleDatafeed(
defaultProps.datafeedUrl,
),
interval:
defaultProps.interval as ChartingLibraryWidgetOptions["interval"],
container_id:
defaultProps.containerId as ChartingLibraryWidgetOptions["container_id"],
library_path: defaultProps.libraryPath as string,
auto_save_delay: 5,
locale: "en",
disabled_features: ["use_localstorage_for_settings"],
enabled_features: ["study_templates"],
load_last_chart: true,
client_id: defaultProps.clientId,
user_id: defaultProps.userId,
fullscreen: defaultProps.fullscreen,
autosize: defaultProps.autosize,
studies_overrides: defaultProps.studiesOverrides,
theme: defaultProps.theme === "Dark" ? "Dark" : "Light",
overrides: {
...savedProperties,
"mainSeriesProperties.candleStyle.upColor": "#41C77A",
"mainSeriesProperties.candleStyle.downColor": "#F23B69",
"mainSeriesProperties.candleStyle.borderUpColor": "#41C77A",
"mainSeriesProperties.candleStyle.borderDownColor": "#F23B69",
"mainSeriesProperties.candleStyle.wickUpColor": "#41C77A",
"mainSeriesProperties.candleStyle.wickDownColor": "#F23B69",
"background": "#141424 ",
"backgroundColor" : "#141424 "
},
// #ts-ignore
save_load_adapter: saveLoadAdapter,
settings_adapter: {
initialSettings: {
"trading.orderPanelSettingsBroker": JSON.stringify({
showRelativePriceControl: false,
showCurrencyRiskInQty: false,
showPercentRiskInQty: false,
showBracketsInCurrency: false,
showBracketsInPercent: false
}),
// "proterty"
"trading.chart.proterty":
localStorage.getItem("trading.chart.proterty") ||
JSON.stringify({
hideFloatingPanel: 1
}),
"chart.favoriteDrawings":
localStorage.getItem("chart.favoriteDrawings") ||
JSON.stringify([]),
"chart.favoriteDrawingsPosition":
localStorage.getItem("chart.favoriteDrawingsPosition") ||
JSON.stringify({})
},
setValue: (key, value) => {
localStorage.setItem(key, value);
},
removeValue: (key) => {
localStorage.removeItem(key);
}
}
};
const tvWidget = new widget(widgetOptions);
tvWidget.onChartReady(() => {
tvWidgetRef.current = tvWidget;
tvWidget
// #ts-ignore
.subscribe("onAutoSaveNeeded", () => tvWidget.saveChartToServer());
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [market, tvWidgetRef.current]);
return <div id={defaultProps.containerId} className={"TVChartContainer"} />;
};
function useTvDataFeed() {
throw new Error("Function not implemented.");
}
ps: i've tried to implement this project : https://github.com/project-serum/serum-dex-ui
I am using react quill as rich text editor and I have used quill mention for adding hashtags and people mention in editor. I have went through the docs of quill mention but there is no example for adding links to inserted "hashtag" or "mention".
There is prop, "linkTarget" for adding link but there is no example for addition of link to hashtag and mention.
Hashvalues and atvalues from database:
hashvalues:[{
id:1,
value:"newHashtag"
}]
atvalues:[{
id:1,
value:"Jhon"
}]
So my expected output is:
for hashtag:
<a href:`/#/hashtags/${id}`>#{value}</a>
for people mention:
<a href:`/#/people/${id}`>#{value}</a>
Here's my code for text editor and mention module:
import React, { useEffect, useState } from "react";
import ReactQuill, { Quill } from "react-quill";
import * as Emoji from "quill-emoji";
import "react-quill/dist/quill.snow.css";
import "quill-emoji/dist/quill-emoji.css";
import "quill-mention/dist/quill.mention.css";
import "quill-mention";
//Add https to link if https is not present
const Link = Quill.import("formats/link");
Link.sanitize = function (url) {
// quill by default creates relative links if scheme is missing.
if (!url.startsWith("http://") && !url.startsWith("https://")) {
return `http://${url}`;
}
return url;
};
Quill.register(Link, true);
Quill.register("modules/emoji", Emoji);
// Add sizes to whitelist and register them
const Size = Quill.import("formats/size");
Size.whitelist = ["extra-small", "small", "medium", "large"];
Quill.register(Size, true);
// Add fonts to whitelist and register them
const Font = Quill.import("formats/font");
Font.whitelist = [
"arial",
"comic-sans",
"courier-new",
"georgia",
"helvetica",
"lucida",
];
Quill.register(Font, true);
let atValues = [];
let hashValues = [];
const mention = {
allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
mentionDenotationChars: ["#", "#"],
linkTarget:"https://www.google.com",
source: function (searchTerm, renderList, mentionChar, ) {
let values;
if (mentionChar === "#") {
values = atValues;
} else {
values = hashValues;
}
if (searchTerm.length === 0) {
renderList(values, searchTerm);
} else {
const matches = [];
for (let i = 0; i < values.length; i++)
if (~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase()))
matches.push(values[i]);
renderList(matches, searchTerm);
}
},
};
function Editor(props) {
const [editorHtml, setEditorHtml] = useState("");
const handleChange = (html) => {
setEditorHtml(html);
props.changeHandler(html);
};
useEffect(() => {
if (props.value) {
setEditorHtml(props.value);
} else {
setEditorHtml("");
}
if(props.values){
let hash=props.values
hash.map((v) => {
v["value"] = v["display"]
})
hashValues=hash
}
if(props.people){
let peoples = props.people
peoples.map((v) => {
v["value"] = v["display"]
})
atValues=peoples
}
}, [props.value]);
return (
<div>
<ReactQuill
onChange={handleChange}
value={editorHtml}
modules={modules}
formats={formats}
bounds={".app"}
placeholder={props.placeholder}
/>
</div>
);
}
const modules = {
toolbar: [
[{ header: [1, 2, 3, 4, 5, 6, false] }],
[{ list: "ordered" }, { list: "bullet" }],
["bold", "italic", "underline"],
[{ color: [] }, { background: [] }],
// [{ script: 'sub' }, { script: 'super' }],
[{ align: [] }],
["link", "blockquote", "emoji"],
["clean"],
],
clipboard: {
// toggle to add extra line breaks when pasting HTML:
matchVisual: false,
},
mention,
"emoji-toolbar": true,
"emoji-textarea": false,
"emoji-shortname": true,
};
const formats = [
"header",
"font",
"size",
"bold",
"italic",
"underline",
"strike",
"blockquote",
"list",
"bullet",
"indent",
"link",
"mention",
"emoji",
];
export default function EMTextArea({
placeHolder,
name,
value,
changeHandler,
hash,
peopleMention
}) {
return (
<div className="custom-toolbar-example">
<Editor
placeholder={placeHolder}
name={name}
value={value}
changeHandler={changeHandler}
values={hash}
people={peopleMention}
/>
</div>
);
}
How can I achieve this?
Thank You!
I solved it, I had to add "link" key in atvalues and hashvalues array of objects.
New hashvalues:
hashvalues:[{
id:1,
value:"hashtag",
link:"/#/users/hashtags/1"}]
And in mention module:
const mention = {
allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
mentionDenotationChars: ["#", "#"],
linkTarget: '_self',
source: function (searchTerm, renderList, mentionChar, ) {
let values;
if (mentionChar === "#") {
values = atValues;
} else {
values = hashValues;
}
if (searchTerm.length === 0) {
renderList(values, searchTerm);
} else {
const matches = [];
for (let i = 0; i < values.length; i++)
if (~values[i].value.toLowerCase().indexOf(searchTerm.toLowerCase()))
matches.push(values[i]);
renderList(matches, searchTerm);
}
},
};
Thanks, anyway.
I am trying to render multiple checkboxes that have two functions:
Show two states: checked and unchecked
Update a checked array with the checked checkboxes
Currently, I am successfully able to accomplish these two goals with dummy data:
const dummyPlayers = [
{ id: 1, name: 'Puppa' },
{ id: 2, name: 'Korvo' },
{ id: 3, name: 'Jesse' },
{ id: 4, name: 'Terry' },
{ id: 5, name: 'Gobblins' }
]
This is the shape of the array I want to populate the checkboxes with:
[
{
"id": "936d6050-00df-4bd4-bc54-6ce58ad0210c",
"name": "Travis",
"owner": "moralesfam",
"type": "Member",
"createdAt": "2021-09-24T20:08:02.292Z",
"updatedAt": "2021-09-24T20:08:02.292Z"
}...
]
However, when I start pulling data in from a database with Graphql, while I am able to render the checkboxes to the DOM, they are not interactive (don't show checked state) and don't log the checked checkboxes.
I bring in the data, an array of objects through a custom React hook, called useMembers and the data is stored in a members array. Console logging members prints out the array, but as soon as I swap the dummyPlayers for the members array, the two goals I stated earlier are unsuccessful.
// RecordGame.js
import React, { useState } from 'react'
import useLoadMembers from '../hooks/useLoadMembers'
import useUser from '../hooks/useUser'
function RecordGame() {
const dummyPlayers = [
{ id: 1, name: 'Puppa' },
{ id: 2, name: 'Korvo' },
{ id: 3, name: 'Jesse' },
{ id: 4, name: 'Terry' },
{ id: 5, name: 'Gobblins' },
]
const { members } = useLoadMembers(updateLoading)
const { user } = useUser()
const [checkedState, setCheckedState] = useState(
new Array(members.length).fill(false)
)
let playingPlayers = []
for (var index in checkedState) {
if (checkedState[index] === true) {
playingPlayers.push(dummyPlayers[index])
}
}
console.log(playingPlayers)
const handleOnChange = (position) => {
const updatedCheckedState = checkedState.map((player, index) =>
index === position ? !player : player
)
setCheckedState(updatedCheckedState)
}
// Rendered elements
const playerCheckboxes = dummyPlayers.map((player, index) => {
return (
<div key={index}>
<label htmlFor={player.name}>
<input
type="checkbox"
id={player.name}
name={player.name}
checked={checkedState[index]}
onChange={() => handleOnChange(index)}
/>
<span> {player.name}</span>
</label>
</div>
)
})
return (
<div>
<form>
{/* Game Players */}
<div>
<label htmlFor="players">
Who Played?
</label>
<div>{playerCheckboxes}</div>
</div>
</form>
</div>
)}
</Dashboard>
)
}
export default RecordGame
//useLoadMember.js
import { useState, useEffect } from 'react'
import { API, Auth } from 'aws-amplify'
import { listMembers } from '../graphql/queries'
const useLoadMembers = (updateLoading) => {
const [members, updateMembers] = useState([])
useEffect(() => {
fetchMembers()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const fetchMembers = async () => {
try {
let memberData = await API.graphql({
query: listMembers,
variables: { limit: 100 },
})
updateLoading(false)
let allMembers = memberData.data.listMembers.items
setFilteredMembers(allMembers)
} catch (err) {
console.error(err)
}
}
const setFilteredMembers = async (allMembers) => {
const { username } = await Auth.currentAuthenticatedUser()
const myMemberData = allMembers.filter((p) => p.owner === username)
updateMembers(myMemberData)
}
return { members }
}
export default useLoadMembers
In this first, picture, I used the dummyPlayers array and got the results I wanted.
However, in this second screenshot, I replaced the dummyData with the members array and did not get any results I wanted.
I'm just confused on why I am getting different results with the same array shape.
wherever you use members you will need to check that members is not undefined before it gets used. If the api calls are not complete, it will get set initially as undefined.
eg: members && members.map(() => ....)
I'm trying to write this React component that connects to an API that returns JSON.
The API returns JSON results that look like this small example:
JSON:
{
"id": 22,
"gameTitle": "The Haunted Plains II",
"startDate": "2020-03-31T12:49:50.009",
"endDate": "2020-04-04T04:00:00",
"description": "A simple bitmap style RPG",
"gameUrl": "https://yourgames.org/1/55/3",
"isOpen": true,
"gameFaqId": 25,
"gameTypeId": 3,
"gameCharClasses": ["Bard", "Theif", "Warrior", "Wizard", "Cleric"]
},
{
"id": 25,
"gameTitle": "Downhill Mountain Biking Pro",
"startDate": "2020-02-12T11:22:30.011",
"endDate": "2020-05-02T03:11:00",
"description": "A side-scrolling, downhill mountaining biking game",
"gameUrl": "https://yourgames.org/3/43/6",
"isOpen": true,
"gameFaqId": 11,
"gameTypeId": 6,
"gameCharClasses": ["Beginner", "Pro", "Super Star"]
}
I want to put the data into the 'gameListing' variable that have defined as 'const gameListing'.
Then I have a function called makeData that is called by the main app which is using a React library called 'react-table'.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const [data, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const result = await axios(
'https://localhost:44376/api/projects',
);
setData(result.data);
};
fetchData();
}, []);
const range = len => {
const arr = [];
for (let i = 0; i < len; i++) {
arr.push(i);
}
return arr;
};
const gameListing = data.map(g => {
return {
id: g.id,
gameTitle: g.gameTitle,
startDate: g.startDate,
endDate: g.endDate,
description: g.description,
gameUrl: g.gameUrl,
isOpen: g.isOpen,
gameFaqId: g.gameFaqId,
gameCharClasses: g.gameCharClasses
};
});
export default function makeData(lens = [2]) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...gameListing(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
The problem is, after hours of debugging, I can't get it to work.
My latest issue is that it's not displaying any data.
Here is a Code Sandbox: https://codesandbox.io/s/trusting-booth-b7wxg
I see one problem is youre using .map wrong
you have to pass in a parameter and that parameter is basically like a placeholder to use that has the data within it
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
for example:
const gameListing = data.map((elem) => {
return {
id: elem.id,
gameTitle: elem.gameTitle,
startDate: elem.startDate,
endDate: elem.endDate,
description: elem.description,
gameUrl: elem.gameUrl,
isOpen: elem.isOpen,
gameFaqId: elem.gameFaqId,
gameCharClasses: elem.gameCharClasses
}
})
Does that help or work?