├── public ├── favicon.ico ├── manifest.json └── index.html ├── src ├── utils │ └── typography.js ├── App.test.js ├── index.css ├── index.js ├── App.css ├── App.js ├── dc │ ├── dayOfWeekChart.js │ ├── quarterChart.js │ ├── gainOrLessChart.js │ ├── fluctuationChart.js │ ├── nasdaqTable.js │ ├── cxContext.js │ ├── chartTemplate.js │ ├── dashboard.js │ ├── moveChart.js │ └── bubbleChart.js ├── welcome.js ├── logo.svg └── serviceWorker.js ├── .gitignore ├── package.json └── README.md /public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LightTag/dcjs-in-react/HEAD/public/favicon.ico -------------------------------------------------------------------------------- /src/utils/typography.js: -------------------------------------------------------------------------------- 1 | import Typography from 'typography'; 2 | import funstonTheme from 'typography-theme-funston' 3 | const typography = new Typography(funstonTheme) 4 | const rhythm = typography.rhythm; 5 | 6 | export { typography, rhythm }; 7 | -------------------------------------------------------------------------------- /src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | } 10 | ], 11 | "start_url": ".", 12 | "display": "standalone", 13 | "theme_color": "#000000", 14 | "background_color": "#ffffff" 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 5 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 6 | sans-serif; 7 | -webkit-font-smoothing: antialiased; 8 | -moz-osx-font-smoothing: grayscale; 9 | } 10 | 11 | code { 12 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 13 | monospace; 14 | } 15 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: http://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /src/App.css: -------------------------------------------------------------------------------- 1 | .App { 2 | text-align: center; 3 | } 4 | 5 | .App-logo { 6 | animation: App-logo-spin infinite 20s linear; 7 | height: 40vmin; 8 | pointer-events: none; 9 | } 10 | 11 | .App-header { 12 | background-color: #282c34; 13 | min-height: 100vh; 14 | display: flex; 15 | flex-direction: column; 16 | align-items: center; 17 | justify-content: center; 18 | font-size: calc(10px + 2vmin); 19 | color: white; 20 | } 21 | 22 | .App-link { 23 | color: #61dafb; 24 | } 25 | 26 | @keyframes App-logo-spin { 27 | from { 28 | transform: rotate(0deg); 29 | } 30 | to { 31 | transform: rotate(360deg); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/App.js: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import logo from "./logo.svg"; 3 | import {typography} from './utils/typography' 4 | import { Dashboard } from "./dc/dashboard"; 5 | import { Welcome } from "./welcome"; 6 | import { Grid } from "react-flexbox-grid"; 7 | import { css } from "glamor"; 8 | 9 | class App extends Component { 10 | 11 | render() { 12 | const style = css({ 13 | background: `#ddd` 14 | 15 | }) 16 | typography.injectStyles() 17 | return ( 18 |
19 | 20 | 21 | 22 | 23 |
24 | ); 25 | } 26 | } 27 | 28 | export default App; 29 | -------------------------------------------------------------------------------- /src/dc/dayOfWeekChart.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as dc from "dc"; 3 | import { ChartTemplate } from "./chartTemplate"; 4 | 5 | const dayOfWeekFunc = (divRef, ndx) => { 6 | const dayOfWeekChart = dc.rowChart(divRef) 7 | const dimension = ndx.dimension(function (d) { 8 | var day = d.dd.getDay(); 9 | var name = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; 10 | return day + '.' + name[day]; 11 | }); 12 | const group = dimension.group() 13 | dayOfWeekChart 14 | .dimension(dimension) 15 | .group(group) 16 | 17 | return dayOfWeekChart 18 | } 19 | 20 | export const DayOfWeekChart = props => ( 21 | 22 | ) 23 | 24 | -------------------------------------------------------------------------------- /src/dc/quarterChart.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as dc from "dc"; 3 | import { ChartTemplate } from "./chartTemplate"; 4 | 5 | const quarterChartFunc = (divRef, ndx) => { 6 | const dimension = ndx.dimension((d) => { 7 | var month = d.dd.getMonth(); 8 | if (month <= 2) { 9 | return 'Q1'; 10 | } else if (month > 2 && month <= 5) { 11 | return 'Q2'; 12 | } else if (month > 5 && month <= 8) { 13 | return 'Q3'; 14 | } else { 15 | return 'Q4'; 16 | } 17 | }); 18 | const group =dimension.group().reduceSum((d)=>d.volume) 19 | 20 | const quarterChart = dc.pieChart(divRef); 21 | quarterChart /* dc.pieChart('#quarter-chart', 'chartGroup') */ 22 | .innerRadius(30) 23 | .dimension(dimension) 24 | .group(group); 25 | return quarterChart 26 | 27 | } 28 | 29 | export const QuarterChart = props => ( 30 | 31 | ) 32 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "dc-react-test", 3 | "homepage": "https://lighttag.github.io/dcjs-in-react", 4 | "version": "0.1.0", 5 | "private": true, 6 | "dependencies": { 7 | "crossfilter2": "^1.4.6", 8 | "d3": "^5.9.1", 9 | "dc": "^2.2.2", 10 | "glamor": "^2.20.40", 11 | "react": "^16.8.2", 12 | "react-dom": "^16.8.2", 13 | "react-flexbox-grid": "^2.1.2", 14 | "react-scripts": "2.1.5", 15 | "react-typography": "^0.16.18", 16 | "typography": "^0.16.18", 17 | "typography-theme-funston": "^0.16.18" 18 | }, 19 | "scripts": { 20 | "start": "react-scripts start", 21 | "build": "react-scripts build", 22 | "test": "react-scripts test", 23 | "eject": "react-scripts eject", 24 | "predeploy": "npm run build", 25 | "deploy": "gh-pages -d build" 26 | 27 | }, 28 | "eslintConfig": { 29 | "extends": "react-app" 30 | }, 31 | "browserslist": [ 32 | ">0.2%", 33 | "not dead", 34 | "not ie <= 11", 35 | "not op_mini all" 36 | ], 37 | "devDependencies": { 38 | "gh-pages": "^2.0.1" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/dc/gainOrLessChart.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as dc from "dc"; 3 | import { ChartTemplate } from "./chartTemplate"; 4 | const gainOrLossChartFunc = (divRef, ndx) => { 5 | const dimension = ndx.dimension(d=> d.open > d.close ? 'Loss' : 'Gain') 6 | const group = dimension.group(); 7 | const all = ndx.groupAll(); 8 | 9 | 10 | 11 | const gainOrLossChart = dc.pieChart(divRef); 12 | gainOrLossChart 13 | .dimension(dimension) 14 | .group(group) 15 | .label(function (d) { 16 | if (gainOrLossChart.hasFilter() && !gainOrLossChart.hasFilter(d.key)) { 17 | return d.key + '(0%)'; 18 | } 19 | var label = d.key; 20 | if (all.value()) { 21 | label += '(' + Math.floor(d.value / all.value() * 100) + '%)'; 22 | } 23 | return label; 24 | }) 25 | .renderLabel(true) 26 | .innerRadius(4) 27 | .transitionDuration(500) 28 | // .colors(['#3182bd', '#6baed6', '#9ecae1', '#c6dbef', '#dadaeb']) 29 | // .colorDomain([-1750, 1644]) 30 | .colorAccessor(d=>d.value) 31 | return gainOrLossChart; 32 | 33 | 34 | 35 | 36 | 37 | 38 | } 39 | 40 | export const GainOrLossChart = props => ( 41 | 42 | ) 43 | -------------------------------------------------------------------------------- /src/dc/fluctuationChart.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as dc from "dc"; 3 | import {scaleLinear } from "d3"; 4 | import { ChartTemplate } from "./chartTemplate"; 5 | import { numberFormat } from "./cxContext"; 6 | 7 | const fluctuationChartFunc = (divRef, ndx) => { 8 | const fluctuationChart = dc.barChart(divRef) 9 | const dimension = ndx.dimension(d=> Math.round((d.close - d.open) / d.open * 100)); 10 | const group =dimension.group() 11 | fluctuationChart 12 | .dimension(dimension) 13 | .group(group) 14 | .gap(1) 15 | .x(scaleLinear().domain([-25, 25])) 16 | .valueAccessor(x=>Math.log10(1+x.value)) 17 | .centerBar(true) 18 | .round(dc.round.floor) 19 | .renderHorizontalGridLines(true) 20 | .filterPrinter( (filters) => { 21 | var filter = filters[0], s = ''; 22 | s += numberFormat(filter[0]) + '% -> ' + numberFormat(filter[1]) + '%'; 23 | return s; 24 | }); 25 | 26 | 27 | 28 | 29 | 30 | fluctuationChart.xAxis().tickFormat( 31 | function (v) { return v + '%'; }); 32 | fluctuationChart.yAxis().ticks(5); 33 | 34 | 35 | return fluctuationChart 36 | } 37 | 38 | export const FluctuationChart = props => ( 39 | 40 | ) 41 | 42 | -------------------------------------------------------------------------------- /src/welcome.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import {css} from 'glamor' 3 | 4 | export const Welcome =(props)=>{ 5 | 6 | return( 7 |
8 |

9 | Using DC.js in React 10 |

11 |
12 | DC.js is a charting library based on 13 | crossfilter and d3. 14 |
It allows creating interactive charts with a significant wow factor
15 | Read the Blog Post! 16 |
17 |

18 | What is this ? 19 |

20 |
21 | This page shows an implementation of the canonical dc.js example, in React. We love dc.js and we love React, 22 | but it sometimes felt they did not love each other. The implementation demonstrated here uses React hooks to 23 | get everyone to play along 24 |
25 |

26 | Who Made This ? 27 |

28 |
29 | LightTag! LightTag makes tools to label NLP data with teams. 30 |
31 |

Click on Things in These Charts

32 |
33 | ) 34 | } -------------------------------------------------------------------------------- /src/dc/nasdaqTable.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as dc from "dc"; 3 | import "dc/dc.css"; 4 | 5 | import {format as d3Format } from 'd3' 6 | import { ChartTemplate } from "./chartTemplate"; 7 | import { numberFormat } from "./cxContext"; 8 | import {css} from 'glamor' 9 | import { rhythm } from "../utils/typography"; 10 | const tableFunc = (divRef, ndx) => { 11 | const nasdaqTable = dc.dataTable(divRef); 12 | 13 | const dimension = ndx.dimension(d=> d.dd); 14 | nasdaqTable.dimension(dimension) 15 | .group(d=>{ 16 | var format = d3Format('02d'); 17 | return d.dd.getFullYear() + '/' + format((d.dd.getMonth() + 1)); 18 | }) 19 | .columns([ 20 | 'date', 21 | 'open', 22 | 'close', 23 | { 24 | label: 'Change', 25 | format: function (d) { 26 | return numberFormat(d.close - d.open); 27 | } 28 | }, 29 | 'volume' 30 | 31 | 32 | ]) 33 | .sortBy(function (d) { 34 | return d.dd; 35 | }) 36 | .on('renderlet', function (table) { 37 | table.selectAll('.dc-table-group').classed('info', true); 38 | }); 39 | 40 | return nasdaqTable; 41 | 42 | } 43 | const style = css({ 44 | '& tr':{ 45 | '&:hover':{ 46 | background:'#dddd' 47 | } 48 | }, 49 | '& td':{ 50 | // padding:rhythm(0.1), 51 | textAlign:'left', 52 | borderTop:'1px solid #ddd', 53 | 54 | } 55 | }) 56 | export const DataTable = props => ( 57 | 58 | ) -------------------------------------------------------------------------------- /src/dc/cxContext.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as crossfilter from "crossfilter2"; 3 | import {csv,timeFormat,timeParse,timeMonth,format} from 'd3' 4 | import "dc/dc.css"; 5 | 6 | export const CXContext = React.createContext("CXContext"); 7 | export const dateFormatSpecifier = '%m/%d/%Y'; 8 | export const dateFormat = timeFormat(dateFormatSpecifier); 9 | export const dateFormatParser = timeParse(dateFormatSpecifier); 10 | export const numberFormat = format('.2f'); 11 | 12 | export class DataContext extends React.Component { 13 | constructor(props) { 14 | super(props); 15 | this.state={loading:false,hasNDX:false}; 16 | } 17 | 18 | componentDidMount(){ 19 | if (this.state.hasNDX){ 20 | return 21 | } 22 | if(this.state.loading){ 23 | return 24 | } 25 | this.setState({loading:true}) 26 | csv('./ndx.csv') 27 | .then((data)=> { 28 | data.forEach(function (d) { 29 | d.dd = dateFormatParser(d.date); 30 | d.month = timeMonth(d.dd); // pre-calculate month for better performance 31 | d.close = +d.close; // coerce to number 32 | d.open = +d.open; 33 | }); 34 | 35 | this.ndx = crossfilter(data); //TODO possibly need to update this 36 | this.setState({loading:false,hasNDX:true}) 37 | 38 | 39 | 40 | }) 41 | 42 | 43 | } 44 | 45 | render() { 46 | if(!this.state.hasNDX){ 47 | return null; 48 | } 49 | return ( 50 | 51 |
52 | {this.props.children} 53 |
54 |
55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 10 | 11 | 15 | 16 | 25 | React App 26 | 27 | 28 | 29 |
30 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/dc/chartTemplate.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { CXContext } from "./cxContext"; 3 | import * as dc from "dc"; 4 | import { rhythm } from "../utils/typography"; 5 | import { css } from "glamor"; 6 | 7 | const ResetButton = props => { 8 | const style = css({ 9 | padding: rhythm(0.1), 10 | display: "inline", 11 | cursor:'pointer', 12 | float:'right', 13 | '&:hover':{ 14 | background: "#ddd", 15 | } 16 | }); 17 | return ( 18 | { 21 | props.chart.filterAll(); 22 | dc.redrawAll(); 23 | }} 24 | > 25 | reset 26 | 27 | ); 28 | }; 29 | export const ChartTemplate = props => { 30 | /* 31 | We render the dc chart using an effect. We want to pass the chart as a prop after the dc call, 32 | but there is nothing by default to trigger a re-render and the prop, by default would be undefined. 33 | To solve this, we hold a state key and increment it after the effect ran. 34 | By passing the key to the parent div, we get a rerender once the chart is defined. 35 | */ 36 | const context = React.useContext(CXContext); 37 | const [chart,updateChart] = React.useState(null); 38 | const ndx = context.ndx; 39 | const div = React.useRef(null); 40 | React.useEffect(() => { 41 | const newChart = props.chartFunction(div.current, ndx); // chartfunction takes the ref and does something with it 42 | 43 | newChart.render(); 44 | updateChart(newChart); 45 | },1); {/*Run this exactly once */} 46 | 47 | const chartStyles = css({ 48 | width:'100%', 49 | height:'auto', 50 | boxSizing:'border-box', 51 | padding:rhythm(1), 52 | '& label':{ 53 | textTransform:'capitalize', 54 | textDecoration:'underline' 55 | 56 | } 57 | 58 | }) 59 | return ( 60 |
64 | 65 | 66 | 67 |
68 | ); 69 | }; 70 | -------------------------------------------------------------------------------- /src/dc/dashboard.js: -------------------------------------------------------------------------------- 1 | import React from 'react' 2 | import {Grid,Row,Col} from 'react-flexbox-grid' 3 | import { BubbleChart } from "./bubbleChart"; 4 | import { GainOrLossChart } from "./gainOrLessChart"; 5 | import { QuarterChart } from "./quarterChart"; 6 | import { DayOfWeekChart } from "./dayOfWeekChart"; 7 | import { FluctuationChart } from "./fluctuationChart"; 8 | import { MoveChart } from "./moveChart"; 9 | import { DataTable } from "./nasdaqTable"; 10 | import { DataContext } from "./cxContext"; 11 | import { css } from 'glamor'; 12 | 13 | export const Dashboard = (props)=>{ 14 | 15 | const style = css({ 16 | padding:'1rem', 17 | marginTop:'2rem' 18 | }) 19 | return( 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 |
56 | ) 57 | } 58 | -------------------------------------------------------------------------------- /src/dc/moveChart.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as dc from "dc"; 3 | import { scaleTime, timeMonth, timeMonths } from "d3"; 4 | import { ChartTemplate } from "./chartTemplate"; 5 | import { dateFormat, numberFormat } from "./cxContext"; 6 | const reducerAdd = (p, v) => { 7 | ++p.days; 8 | p.total += (v.open + v.close) / 2; 9 | p.avg = Math.round(p.total / p.days); 10 | return p; 11 | }; 12 | 13 | const reducerRemove = (p, v) => { 14 | --p.days; 15 | p.total -= (v.open + v.close) / 2; 16 | p.avg = p.days ? Math.round(p.total / p.days) : 0; 17 | return p; 18 | }; 19 | 20 | const reducerInitial = () => ({ days: 0, total: 0, avg: 0 }); 21 | const moveChartFunc = (divRef, ndx) => { 22 | const dimension = ndx.dimension(d => d.month); 23 | 24 | const moveChart = dc.lineChart(divRef); 25 | const monthlyMoveGroup = dimension 26 | .group() 27 | .reduceSum(d => Math.abs(d.close - d.open)); 28 | const indexAvgByMonthGroup = dimension 29 | .group() 30 | .reduce(reducerAdd, reducerRemove, reducerInitial); 31 | 32 | moveChart 33 | .dimension(dimension) 34 | .mouseZoomable(true) 35 | .transitionDuration(1000) 36 | .x(scaleTime().domain([new Date(1985, 0, 1), new Date(2012, 11, 31)])) 37 | .round(timeMonth.round) 38 | .xUnits(timeMonths) 39 | .elasticY(true) 40 | .renderHorizontalGridLines(true) 41 | .legend( 42 | dc 43 | .legend() 44 | .x(800) 45 | .y(10) 46 | .itemHeight(13) 47 | .gap(5) 48 | ) 49 | .brushOn(false) 50 | .group(indexAvgByMonthGroup, "Monthly Index Average") 51 | .valueAccessor(function(d) { 52 | return d.value.avg; 53 | }) 54 | .stack(monthlyMoveGroup, "Monthly Index Move", function(d) { 55 | return d.value; 56 | }) 57 | .title(function(d) { 58 | var value = d.value.avg ? d.value.avg : d.value; 59 | if (isNaN(value)) { 60 | value = 0; 61 | } 62 | return dateFormat(d.key) + "\n" + numberFormat(value); 63 | }); 64 | 65 | return moveChart; 66 | }; 67 | 68 | export const MoveChart = props => ( 69 | 70 | ) 71 | -------------------------------------------------------------------------------- /src/logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /src/dc/bubbleChart.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import * as dc from "dc"; 3 | import { timeYear, schemeRdYlGn, scaleLinear } from "d3"; 4 | import { numberFormat } from "./cxContext"; 5 | import { ChartTemplate } from "./chartTemplate"; 6 | 7 | const groupAddReducer =(p,v)=>{ 8 | ++p.count; 9 | p.absGain += v.close - v.open; 10 | p.fluctuation += Math.abs(v.close - v.open); 11 | p.sumIndex += (v.open + v.close) / 2; 12 | p.avgIndex = p.sumIndex / p.count; 13 | p.percentageGain = p.avgIndex ? (p.absGain / p.avgIndex) * 100 : 0; 14 | p.fluctuationPercentage = p.avgIndex 15 | ? (p.fluctuation / p.avgIndex) * 100 16 | : 0; 17 | return p; 18 | } 19 | const groupRemoveRudcer =(p, v) =>{ 20 | --p.count; 21 | p.absGain -= v.close - v.open; 22 | p.fluctuation -= Math.abs(v.close - v.open); 23 | p.sumIndex -= (v.open + v.close) / 2; 24 | p.avgIndex = p.count ? p.sumIndex / p.count : 0; 25 | p.percentageGain = p.avgIndex ? (p.absGain / p.avgIndex) * 100 : 0; 26 | p.fluctuationPercentage = p.avgIndex ? (p.fluctuation / p.avgIndex) * 100 : 0; 27 | return p; 28 | } 29 | 30 | const groupInitalizer = ()=> { 31 | return { 32 | count: 0, 33 | absGain: 0, 34 | fluctuation: 0, 35 | fluctuationPercentage: 0, 36 | sumIndex: 0, 37 | avgIndex: 0, 38 | percentageGain: 0 39 | }; 40 | } 41 | 42 | const bubbleChartFunc = (divRef, ndx) => { 43 | const yearlyDimension = ndx.dimension(d => timeYear(d.dd).getFullYear()); 44 | const yearlyPerformanceGroup = yearlyDimension.group() 45 | .reduce(groupAddReducer,groupRemoveRudcer,groupInitalizer); 46 | const yearlyBubbleChart = dc.bubbleChart(divRef); // Divref is a refere3nce to the div we're attaching to 47 | yearlyBubbleChart 48 | .transitionDuration(1500) 49 | .dimension(yearlyDimension) 50 | .group(yearlyPerformanceGroup) 51 | .colors(schemeRdYlGn[9]) // why the 9 ? 52 | .colorAccessor(d => d.value.absGain) 53 | .keyAccessor(p => p.value.absGain) 54 | .valueAccessor(p=>p.value.percentageGain) 55 | .radiusValueAccessor(p => p.value.fluctuationPercentage) 56 | .maxBubbleRelativeSize(0.3) 57 | .x(scaleLinear().domain([-2500, 2500])) 58 | .y(scaleLinear().domain([-100, 100])) 59 | .r(scaleLinear().domain([0, 4000])) 60 | .elasticY(false) 61 | .elasticX(true) 62 | .yAxisPadding(100) 63 | .xAxisPadding('10%') 64 | .renderHorizontalGridLines(true) 65 | .renderVerticalGridLines(true) 66 | .xAxisLabel('Index Gain') 67 | .yAxisLabel('Index Gain %') 68 | .renderLabel(true) 69 | .label(p=>p.key) 70 | .renderTitle(true) 71 | .title( (p)=>( 72 | [ 73 | p.key, 74 | 'Index Gain: ' + numberFormat(p.value.absGain), 75 | 'Index Gain in Percentage: ' + numberFormat(p.value.percentageGain) + '%', 76 | 'Fluctuation / Index Ratio: ' + numberFormat(p.value.fluctuationPercentage) + '%' 77 | ].join('\n') 78 | )) 79 | .yAxis().tickFormat(v=>`${v}%`) 80 | return yearlyBubbleChart 81 | 82 | }; 83 | export const BubbleChart = props => ( 84 | 85 | ) 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # React + DC.JS 2 | 3 | This is a POC of using [DC.JS within a React application](https://www.lighttag.io/blog/react-dc-js/). 4 | 5 | [demo](https://lighttag.github.io/dcjs-in-react/), [blog post](https://www.lighttag.io/blog/react-dc-js/) 6 | 7 | ## The Problem 8 | 9 | React is, well React, and DC.JS is a library for making interactive charts and dashboards on high dimensional data. [We](https://www.lighttag.io) want to use DC.JS inside of our react app but they don't play nice. 10 | 11 | DC is powered by D3, which manipulates the DOM. Since React also manipulates the dom this has potential for conflicts and significant cognitive overhead. 12 | 13 | DC is also powered by crossfilter, which manages the state of your data and filters. Generally, we let React manage data/state either directly in state or through something like redux. This also has potential for conflicts and overhead. 14 | 15 | ## The Solution 16 | 17 | ### Keep Crossfilter in a Context Provider 18 | 19 | DC works by keeping a "global" crossfilter object witht he data, and letting the charts apply various filters on it. We tried to put that crossfilter inside of a context object, and render all charts using it. 20 | 21 | You can see the code [here](/src/dc/cxContext.js) but the crux of it is 22 | 23 | ```es6 24 | export class DataContext extends React.Component { 25 | constructor(props) { 26 | super(props); 27 | this.state={loading:false,hasNDX:false}; 28 | } 29 | 30 | componentDidMount(){ 31 | if (this.state.hasNDX){ 32 | return 33 | } 34 | if(this.state.loading){ 35 | return 36 | } 37 | this.setState({loading:true}) 38 | {/*do things here to get data */} 39 | this.ndx = crossfilter(data); //TODO possibly need to update this 40 | this.setState({loading:false,hasNDX:true}) 41 | }) 42 | } 43 | 44 | render() { 45 | if(!this.state.hasNDX){ 46 | 47 | return null; 48 | } 49 | return ( 50 | 51 |
52 | {this.props.children} 53 |
54 |
55 | ); 56 | } 57 | } 58 | 59 | ``` 60 | 61 | ### Create A "Chart Wrapper Component" 62 | 63 | DC uses a declarative syntax to define charts. You give it a DOM element and data from crossfilter, and it gives you a chart back. If you use the same crossfilter object the charts will interact, which is what we want. 64 | 65 | To get this working in react we can break it down into two parts. 1) Is a react component that creates an element and has access to the crossfilter context. 2) Is a function that receives the element and crossfilter object and creates a chart. 66 | 67 | Since part 1 repeats, it makes sense to abstract it into it's own component, which you can find [here](/src/chartTemplate.js) 68 | 69 | A simplified version of it looks like this 70 | 71 | ```es6 72 | export const ChartTemplate = props => { 73 | /* 74 | We render the dc chart using an effect. We want to pass the chart as a prop after the dc call, 75 | but there is nothing by default to trigger a re-render and the prop, by default would be undefined. 76 | To solve this, we 1) hold the chart in state using a hook 2) make sure the effect hook is run exactly once 77 | */ 78 | const context = React.useContext(CXContext); 79 | const [chart,updateChart] = React.useState(null); 80 | const ndx = context.ndx; 81 | const div = React.useRef(null); 82 | React.useEffect(() => { 83 | const newChart = props.chartFunction(div.current, ndx); // chartfunction takes the ref and does something with it 84 | 85 | newChart.render(); 86 | updateChart(newChart); 87 | },1); {/*Run this exactly once */} 88 | return ( 89 |
94 |
95 | ); 96 | }; 97 | 98 | ``` 99 | 100 | ## Making A Chart 101 | 102 | From there, making a new chart is just writing standard dc.js code as a function, and passing that function as a 103 | prop to the template component. Victory! 104 | 105 | ## Brought To You By LightTag 106 | LightTag is a tool for [NLP annotation](https://www.lighttag.io). 107 | -------------------------------------------------------------------------------- /src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read http://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit http://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See http://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | --------------------------------------------------------------------------------