I'm currently following a tutorial in order to learn how to create a dashboard to track cryptocurrency prices. However, I have become stuck on an issue where the top of my tables gets cut off when I run the webpage on chrome , while the top of the webpage is supposed to look like this at the top of the webpage as can be seen when ran on IE . When I disable javascript within Chrome I get something like . The program's backend uses next.js, coingecko API to fetch prices and bootstrap for formatting. I would greatly appreciate any tips that could help in pushing me towards the solution. I have attached the relevant code and resources below.
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import CoinGecko from 'coingecko-api';
const coinGeckoClient = new CoinGecko();
export default function Home(props) {
const { data } = props.result;
const formatPercent = number =>
`${new Number(number).toFixed(2)}%`
const formatDollar = (number, maximumSignificantDigits) =>
new Intl.NumberFormat(
'en-US',
{
style: 'currency',
currency: 'USD',
maximumSignificantDigits
})
.format(number);
return (
<div className={styles.container}>
<Head>
<title>Coinmarketcap clone</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<h1>Coinmarketcap clone</h1>
<table className="table">
<thead>
<tr>
<th>Symbol</th>
<th>24H Change</th>
<th>Price</th>
<th>Market cap</th>
</tr>
</thead>
<tbody>
{data.map(coin => (
<tr key={coin.id}>
<td>
<img
src={coin.image}
style={{width: 25, height: 25, marginRight: 10}}
/>
{coin.symbol.toUpperCase()}
</td>
<td>
<span
className={coin.price_change_percentage_24h > 0 ? (
'text-success'
) : 'text-danger'}
>
{formatPercent(coin.price_change_percentage_24h)}
</span>
</td>
<td>{formatDollar(coin.current_price, 20)}</td>
<td>{formatDollar(coin.market_cap, 12)}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
Tutorial: https://www.youtube.com/watch?v=klFeYge2G0I
Repo: https://github.com/jklepatch/eattheblocks/tree/master/screencast/226-coinmarketcap-clone
Related
import axios from 'axios';
import React, { useEffect, useState } from 'react'
import Navbar from './Navbar'
const Home = () => {
var [Employeelist,setEmployeelist] = useState([]);
useEffect(()=>{
getData();
},[])
const getData=()=>{
axios.get('https://jsonplaceholder.typicode.com/users')
.then((response)=>{
console.log(response.data)
setEmployeelist(response.data)
})
.catch()
}
return (
<div>
<Navbar/>
<br /><br />
<div className="container">
<div className="row">
<div className="col col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12">
<div className="row g-4">
<div className="col col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12">
<h2 style={{textAlign:"center",textDecoration:"underline",fontStyle:'italic'}}>Employee data</h2>
<table class="table table-success table-striped table-hover" style={{border:'solid 2px black', borderRadius:'20px !important'}}>
<thead className="table-dark">
<tr>
<th scope="col">id</th>
<th scope="col">Name</th>
<th scope="col">Email</th>
</tr>
</thead>
{Employeelist.map((value,index)=>{
return <tbody class="table-group-divider">
<tr>
<th scope="row">{value.id}</th>
<td>{value.name}</td>
<td>{value.email}</td>
</tr>
</tbody>
})}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Home
This is my code
When i start the server it shows compiled successfully but nothing shows on the screen and when i open the console it shows "Uncaught SyntaxError: Cannot use import statement outside a module (at bundle.js:47878:2)" I tried adding "type":"module" into the package.json file as shown inn somethreads but still not useful
The issue is, the browser cannot use modules so you need a bundler like (Browserify or Vite) which bundles your modules and code into a single file so it can be used by the browser. More information about modules and bundlers here
I have a dashboard with a table component inside it. I am making a graphql call in the dashboard and need to pass the data recieved into the table like this . However I can't get the data to show up inside the table component.
Here is my approach. Please let me know what I'm missing
Dashboard.js
import React from "react";
import "bootstrap/js/src/collapse.js";
import DashboardTable from "../DashboardTable";
import { API } from "#aws-amplify/api";
import config from "../../aws-exports";
import * as queries from "../../graphql/queries";
export default function Dashboard() {
var opportunityTable;
API.configure(config);
async function asyncCall() {
const opportunityTable = await API.graphql({
query: queries.listMockOppsTables,
});
// console.log(opportunityTable.data.listMockOppsTables); // result: { "data": { "listTodos": { "items": [/* ..... */] } } }
}
asyncCall();
return (
<div>
<div className="container py-5">
<DashboardTable
data={opportunityTable.data.listMockOppsTables}
></DashboardTable>
</div>
</div>
);
}
Table (receiving prop data)
import React from "react";
import "bootstrap/js/src/collapse.js";
require("../opportunityData.json");
export class Opportunity extends React.Component {
constructor(props) {
super(props);
this.state = {
opportunityData: this.props.items,
};
}
render() {
console.log(this.opportunityData);// returns nothing
return (
<div>
<section class="py-5 mt-5">
<div class="container py-5">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Shadow ID</th>
<th>Role Title</th>
<th>Interview Type</th>
<th>Level</th>
<th>Date and Time</th>
<th># Requests</th>
<th>Make Request</th>
</tr>
</thead>
{this.opportunityData.map((opportunity) => (
<tbody>
<tr>
<td>{opportunity.shadow_id}</td>
<td>{opportunity.job_title}</td>
<td>{opportunity.shadow_type}</td>
<td>4</td>
<td>
{opportunity.shadow_datetime}
<br />
{opportunity.shadow_datetime}
</td>
<td>2</td>
<td>
<div class="btn-group" role="group">
<button
class="btn btn-primary"
type="button"
style={{
backgroundColor: "#ff9900",
border: 0,
}}
>
Shadow
</button>
<button
class="btn btn-primary"
type="button"
style={{
backgroundColor: "#ffac2f",
border: 0,
}}
>
Reverse Shadow
</button>
</div>
</td>
</tr>
</tbody>
))}
</table>
</div>
</div>
</section>
</div>
);
}
}
export default Opportunity;
You're problem is either with your method of passing state or with you querying. One issue in your code is by practice in React, you want state to be managed as a stateful value with the useState()hook. You will have to verify your data is loaded before passing it into the hook. This would look like:
const [opportunityTable, changeOpportunityTable] = useState(asyncCall());
Also you should've posted your DashBoardTable component instead of your Oppurtunity component which you don't seem to import in DashBoard to begin with. Here's a little skeleton
const DashBoardTable = ({data}) => {
//whatever code you may need
return (
//other formatting
data.map((key) => {
//access with data.<VARIABLE>
}
);
}
export default DashBoardTable;
I've been fiddling with arrays and mapping them using the Array.prototype.map() fucntion and honestly i've been struggleing ALOT so i hope somebody can share some light on this.
So my goal is simple to map some headings and rows in a table in my custom component, but when i get to make the mapping its always says "variable.map() is not a function" event tho im specifying its an array and it has values im passing on from my page.
I have already tested if its was because it was empty but it doesnt seem that way.
My page is simply this for now.
import AppLayout from '../../../components/AppLayout';
import Table from '../../../components/modules/Table';
export default function Products() {
return (
<AppLayout>
<section className="content">
<h3 className="text-3xl font-bold">Products</h3>
<Table
headings={[
'',
'Product',
'Status',
'Type',
]}
/>
</section>
</AppLayout>
);
}
As for my table its:
export default function Table(headings = [], rows = {}) {
const top = headings.map((value) => (
<th
key={value}
scope="col"
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
{value}
</th>
));
return (
<div className="flex flex-col">
<div className="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div className="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div className="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
{top}
</thead>
<tbody>
{rows}
</tbody>
</table>
</div>
</div>
</div>
</div>
);
}
I've had other issues with mapping arrays but this is the most one i always fail one idk why SO ANNOYING.
Thanks in advance
I checked your mapping and it works fine. I think the problem is with your data extraction. You should modify your code as follow:
export default function Table({headings = [], rows = {}}) {
or
export default function Table(props) {
{headings, rows} = props;
Component props will always be an object, so you need to destructure the properties from that object:
Table({ headings = [], rows = [] })
I've changed rows to an array too because, although you don't pass any row property into that component at the moment, I'm pretty sure that it will also be an array that will also need to be mapped over.
Can anyone explain what's going on here?
On the index page referenced below there is a section where I source data from a WordPress API to generate the four most recent posts from a client. When running in develop mode with Gatsby, the website is presented fine, but when I upload the website to Netlify and build it out, the data disappears and leaves nothing more than an empty set of p tags.
When I go into development tools and step through breakpoints, I notice that the data in question appears on the website, but then disappears once the webpack fires and the modules are bundled. It's almost as if this data is getting overwritten. When I navigate away from this page on the same website, and then return, the p tags HAVE the data in question. I'm assuming the webpack overwrites the initial code, and then when I come back to the page the webpack has already fired so it loads the information fine? How do I work around this? Excuse me if this is a silly/obvious question.
Full code in reference:
import React from "react"
import { Link, graphql, useStaticQuery } from 'gatsby'
import Layout from '../components/layout'
import indexStyles from '../components/modules/index.module.css'
import Carousel from 'nuka-carousel'
import header1 from '../img/header1.jpg'
import header2 from '../img/header2.jpg'
import header3 from '../img/header3.jpg'
const IndexPage = () => {
const data = useStaticQuery(graphql`
query {
allWordpressPost (sort: {fields:date, order:DESC}) {
edges {
node {
title
slug
excerpt
date(formatString:"MMMM DD, YYYY")
}
}
}
}
`)
return (
<Layout>
<div className={indexStyles.indexCarousel_container}>
<Carousel
autoplay={true}
autoplayInterval={5000}
pauseOnHover={false}
wrapAround={true}
renderCenterLeftControls={({ previousSlide }) => (
<button onClick={previousSlide} className={indexStyles.indexCarousel_button}><i className="fas fa-arrow-left"></i></button>
)}
renderCenterRightControls={({ nextSlide }) => (
<button onClick={nextSlide} className={indexStyles.indexCarousel_button}><i className="fas fa-arrow-right"></i></button>
)}>
<div className={indexStyles.indexCarousel_slideContainer}>
<img src={header1} alt="Pencil case with cat, heart, and cupcake design."></img>
<div>
<h2>Shop</h2>
</div>
</div>
<div className={indexStyles.indexCarousel_slideContainer}>
<Link to="/blog"><img src={header2} alt="Notepad next to a cup of coffee."></img></Link>
<div>
<h2>Blog</h2>
</div>
</div>
<div className={indexStyles.indexCarousel_slideContainer}>
<img src={header3} alt="Colorful pencil cases."></img>
<div>
<h2>Cute Castle VIP</h2>
<p>Save 20%!</p>
</div>
</div>
</Carousel>
</div>
<h1 className={indexStyles.indexHeader}>Latest Posts</h1>
<div className={indexStyles.indexPost_container}>
<div className={indexStyles.indexPost_container}>
{data.allWordpressPost.edges.map((edge, i) => {
if (i < 4) {
return (
<div className={indexStyles.index_post}>
<h2><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_title} dangerouslySetInnerHTML={{ __html: edge.node.title }}></Link></h2>
<p className={indexStyles.post_date}>{edge.node.date}</p>
<p className={indexStyles.post_excerpt} dangerouslySetInnerHTML={{ __html: edge.node.excerpt }} />
<p><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_link}>Read more</Link></p>
</div>
)
}
})}
</div>
</div>
</Layout >
)
}
export default IndexPage
The section of code that disappears and reappears:
<div className={indexStyles.indexPost_container}>
<div className={indexStyles.indexPost_container}>
{data.allWordpressPost.edges.map((edge, i) => {
if (i < 4) {
return (
<div className={indexStyles.index_post}>
<h2><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_title} dangerouslySetInnerHTML={{ __html: edge.node.title }}></Link></h2>
<p className={indexStyles.post_date}>{edge.node.date}</p>
<p className={indexStyles.post_excerpt} dangerouslySetInnerHTML={{ __html: edge.node.excerpt }} />
<p><Link to={`/blog/${edge.node.slug}`} className={indexStyles.post_link}>Read more</Link></p>
</div>
)
}
})}
</div>
</div>
A link to the Netlify project.
https://zealous-engelbart-509321.netlify.com/
Thanks in advance for your help!
I am using Dotnet Core 2.2 to generate report with JSReport (https://jsreport.net/)
I use local JsReport so I sent my template and data to the local server and get back the pdf. Now I need to format date in javascript, so I require to include moment.js into my templates. I have no idea how to do that.
In html I need to format StartDate to formated Date using moment.js
I have no idea how to include moment.js into template and how to add helpers.
For JSReport I am using engine chrome-pdf and handlebars as templating engine (https://jsreport.net/learn/handlebars)
I have tried to include moment.js in the
<script src="http://localhost:5000/public/js/moment.js"/>
<script>
function formatDate(date){
return moment(date).format("dd MMMM yyyy");
}
</script>
but when I called {{{formateDate startDate}}}} inside the html template, it seems the function/helpers not recognized.
My C# code:
[HttpGet("reporting")]
public async Task<IActionResult> Test(){
var sdr = await _repo.GetStaffDefaultRates();
var dto = _mapper.Map<List<StaffDefaultRate>, List<ReportDto>>(sdr);
var x = new {
bootstrapcss = "http://localhost:5000/public/css/bootstrap.min.css",
publicPath = "http://localhost:5000/public/",
message = "hello world",
today = DateTime.Now.ToString("dd MMM yyyy"),
staffRates = dto,
};
var staffRates = _fileRepository.ReadReportTemplate("StaffRates.html");
var rs = new ReportingService("http://localhost:5488");
var report = await rs.RenderAsync(new RenderRequest(){
Template = new Template(){
Recipe = Recipe.ChromePdf,
Engine = Engine.Handlebars,
Content = staffRates,
}, Data = x
});
var memory = new MemoryStream();
await report.Content.CopyToAsync(memory);
memory.Position = 0 ;
return File(memory, "application/pdf");
// return Ok(staffRates);
}
My templates:
<html>
<head>
<title> Staff Default Rates</title>
<link href="{{bootstrapcss}}" rel="stylesheet">
</link>
</head>
<body>
<div class="sticky-top">
<div class="row pt-3 header">
<div class="col-6 text-left">
<img src="http://localhost:5000/public/logo-full.jpg" width="100%"></img>
</div>
<div class="col-6 text-right"></div>
</div>
</div>
<div class="container">
<div class="row mt-5">
<div class="col-12 text-center">
<h2>Staff List {{today}}</h2>
<table class="table table-striped">
<thead>
<tr>
<th rowspan="2"> </th>
<th rowspan="2" colspan="1" class="align-middle">Staff Roles</th>
<th > Start Date </th>
</tr>
</thead>
<tbody>
{{#each staffRates}}
<tr>
<td>{{id}}</td>
<td>{{staffType}}</td>
<td class='text-center'>{{startDate}}</td>
</tr>
{{/each}}
</tbody>
</table>
</div>
</div>
</div>
<div class="container">
<div class="row pb-3 footer fixed-bottom">
<div class="col-12 text-center">
<img src="http://localhost:5000/public/footer.jpg" width="100%"></img>
</div>
</div>
</div>
</body>
</html>
The minimal example would look like this.
var result = rs.RenderAsync(new RenderRequest {
Template = new Template
{
Content = "{{myFormat date}}",
Helpers = #"
const moment = require('moment')
function myFormat(d) {
return moment(d).format('dd MMMM yyyy')
}",
Engine = Engine.Handlebars,
Recipe = Recipe.ChromePdf
},
Data = new
{
date = DateTime.Now
}
}).Result;
result.Content.CopyTo(File.OpenWrite("report.pdf"));
Note your server should have local files access enabled. Otherwise the call require('moment') throws. The provided example will work as it is on default jsreport because it has moment module already installed. In case you want to use another custom module you need to install it using npm i mycustommodule.