I am attempting to follow this documentation to create a very simple bar graph, however, it seems as though Salesforce has no idea what is in my D3 static resource as it says ____ is not a function
for anything I try to do with the imported D3 object.
I did exactly what the documentation said:
- Went to D3's GitHub to download the resource files: https://github.com/d3/d3
- Zipped the repo up
- Created a new Static Resource and selected the
d3-master.zip
file as the file for the static resource. - Set the cache control to Public.
And then I went ahead and used this resource provided by D3 to construct a D3 Bar Chart.
I can't figure out what's wrong. I get errors for both D3.scaleLinear
and D3.scaleBand
functions when attempting to set y and x, respectively.
import { LightningElement } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import D3 from '@salesforce/resourceUrl/D3';
export default class YtpReport extends LightningElement {
svgWidth = 400;
svgHeight = 400;
d3Initialized = false;
/**
* Dummy Data Fillers
*/
data = [
{"name": "E", value: "10"},
{"name": "A", value: "15"},
{"name": "I", value: "25"},
{"name": "Y", value: "9"},
{"name": "U", value: "8"},
{"name": "O", value: "3"}
]
/**
* Render the SVG
*/
renderedCallback() {
if (this.d3Initialized) {
return;
}
this.d3Initialized = true;
Promise.all([
loadScript(this, D3 + '/d3.v5.min.js'),
loadStyle(this, D3 + '/style.css'),
])
.then(() => {
this.initializeD3();
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error loading D3',
message: error.body.message,
variant: 'error',
}),
);
});
}
/**
* Calculations
*/
y = D3.scaleLinear()
.domain([0, D3.max(this.data, d => d.value)]).nice()
.range([this.height - this.margin.bottom, this.margin.top])
x = D3.scaleBand()
.domain(this.data.map(d => d.name))
.range([this.margin.left, this.width - this.margin.right])
.paddingInner(0.1)
xAxis = g => g
.attr("transform", `translate(0,${this.height - this.margin.bottom})`)
.call(D3.axisBottom(this.x).tickSizeOuter(0))
yAxis = g => g
.attr("transform", `translate(${this.margin.left},0)`)
.call(D3.axisLeft(this.y))
margin = ({top: 20, right: 0, bottom: 30, left: 40})
/**
* Initialize the data graph
*/
initializeD3() {
const svg = D3.select(this.template.querySelector('svg.d3'));
//const width = this.svgWidth;
//const height = this.svgHeight;
svg.append("g")
.attr("fill", "steelblue")
.selectAll("rect")
.data(this.data)
.join("rect")
.attr("x", d => this.x(d.name))
.attr("y", d => this.y(d.value))
.attr("height", d => this.y(0) - this.y(d.value))
.attr("width", this.x.bandwidth());
svg.append("g")
.call(this.xAxis);
svg.append("g")
.call(this.yAxis);
return svg.node();
}
}
I even tried to copy exactly what they have in the documentation of showing a force-directed graph, and while I don't get any errors, I don't get any graph displayed.