How to customise react-google-charts? - reactjs

I want to customise legends and title of x-Axis and y-Axis in my bar graph. It is a react google chart. Here is my current graph having slanted legends, I want it to be as a graph in second image.
Here is the code for bar graph chart that I want to use.
slanted legend bar graph
required bar graph
'''
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Chart from 'react-google-charts';
import Loader from 'semantic-ui-react/dist/commonjs/elements/Loader';
import Dimmer from 'semantic-ui-react/dist/commonjs/modules/Dimmer';
import ErrorMessage from '../vizTab/ErrorMessage';
class BarGraph extends Component {
state = {}
componentDidUpdate = (prevProps) => {
const { loading, data } = this.props;
if (prevProps.loading !== loading && !loading) {
this.processResponse(data);
}
}
processResponse = (data) => {
try {
const keys = Object.keys(data[0] || {});
const renderArray = [keys].concat(data.map((d) => (
keys.map((key) => d[key])
)));
this.setState({ data: renderArray });
} catch (error) {
this.setState({ data: undefined });
}
}
clicked = (row) => {
const { clicked, data } = this.props;
if (clicked) clicked(data[row]);
}
render = () => {
const {
xAxis, yAxis, orientation, slantedTextAngle, loading, colors, noDataMessage, fullWidth,
groupWidth,
} = this.props;
const { data } = this.state;
let chartType = '';
if (orientation === 'horizontal') {
chartType = 'BarChart';
} else {
chartType = 'ColumnChart';
}
return (
<div
className="container-text large ui card centered"
style={{
height: '100%', width: '100%', boxShadow: 'none', WebkitBoxShadow: 'none',
}}
>
{loading ? (
<Dimmer active inverted>
<Loader>Loading</Loader>
</Dimmer>
) : (
!data || (data && data.length <= 1) ? (
<ErrorMessage noDataMessage={noDataMessage} />
) : (
<Chart
width="100%"
height="100%"
chartType={chartType}
loader={<div>Loading Chart</div>}
data={data}
options={{
hAxis: {
title: xAxis,
legend: { alignment: 'center' },
slantedText: true,
slantedTextAngle: parseInt(slantedTextAngle, 10),
minValue: 0,
},
vAxis: {
title: yAxis, minValue: 0,
},
colors: colors.split(',') || [],
bar: { groupWidth: groupWidth || data.length > 4 ? '60%' : '30%' },
animation: {
duration: 300,
easing: 'linear',
startup: true,
},
chartArea: fullWidth === 't' ? {
left: '50%', width: '80%',
} : undefined,
}}
chartEvents={[
{
eventName: 'ready',
callback: ({ chartWrapper, google }) => {
const chart = chartWrapper.getChart();
google.visualization.events.addListener(
chart,
'click',
(e) => {
const { targetID } = e;
if (targetID && targetID.match('legend')) {
return;
}
const [, row] = targetID.match(/[0-9]+/g) || [];
if (row >= 0) this.clicked(row);
},
);
},
},
]}
/>
)
)}
</div>
);
}
}
BarGraph.propTypes = {
loading: PropTypes.bool,
data: PropTypes.arrayOf(PropTypes.any),
clicked: PropTypes.func,
xAxis: PropTypes.string,
yAxis: PropTypes.string,
orientation: PropTypes.string,
slantedTextAngle: PropTypes.string,
colors: PropTypes.string,
noDataMessage: PropTypes.string,
fullWidth: PropTypes.string,
groupWidth: PropTypes.string,
};
BarGraph.defaultProps = {
loading: false,
data: [],
clicked: null,
xAxis: '',
yAxis: '',
orientation: 'vertical',
slantedTextAngle: '30',
colors: 'green,blue,purple,whisper,red,dodger blue,dark green,maroon,yellow,grey,orange,pink,magenta,teal,brown',
noDataMessage: '',
fullWidth: null,
groupWidth: null,
};
export default BarGraph;
'''

Related

next chart.js how to change date display

how to change date display on my chart? Here below my chart:
How to change date displaying way? Is there any way to display it horizontaly and f.e. not every date, but every third?
Here below my code:
import { ChartProps } from "./Chart.props";
import styles from "./Chart.module.css";
import React, { useState, useEffect, useRef } from 'react';
import { Button } from "../Button/Button";
import { options } from "./ChartConfig.js";
import { Chart as ChartJS, ArcElement, CategoryScale, LinearScale, PointElement, LineElement, Filler, Tooltip, Legend, ScriptableContext, } from "chart.js";
import { Chart as ReactChart, Line } from "react-chartjs-2";
import coinGecko from "../../../apis/coinGecko";
ChartJS.register(ArcElement, Tooltip, Filler, Legend, CategoryScale, LinearScale, PointElement, LineElement);
export const CoinPriceChart = (props) => {
const [timeFormat, setTimeFormat] = useState("30d");
const [interval, setInterval] = useState("hourly");
const [coinPrice, setCoinPrice] = useState([]);
const [coinHistory, setCoinHistory] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const x = [];
const y = [];
const determineTimeFormat = () => {
switch (timeFormat) {
case "1":
setInterval("5min");
setTimeFormat("1");
case "7":
setInterval("hourly");
setTimeFormat("7");
case "30":
setInterval("daily");
setTimeFormat("30");
default:
setInterval("hourly");
}
};
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
await fetch(`https://api.coingecko.com/api/v3/coins/bitcoin/market_chart?vs_currency=usd&days=${timeFormat}&interval=${interval}`)
.then((response) => {
return response.json();
})
.then((data) => {
for (let i = 0; i < data.prices.length; i++) {
x.push(data.prices[i][1])
setCoinPrice(x)
}
for (let i = 0; i < data.prices.length; i++) {
y.push(new Date(data.prices[i][0]).toLocaleDateString("en-GB"))
setCoinHistory(y)
}
})
setIsLoading(false);
};
fetchData();
}, [timeFormat]);
const chart = {
labels: coinHistory,
datasets: [
{
data: coinPrice,
pointRadius: 0,
pointHoverRadius: 2,
backgroundColor: (context: ScriptableContext<"line">) => {
const ctx = context.chart.ctx;
const gradient = ctx.createLinearGradient(0, 0, 0, 330);
gradient.addColorStop(0, "rgba(91,56,237,0.45)");
gradient.addColorStop(1, "rgba(91,56,237,0.0)");
return gradient;
},
borderColor: "rgba(91,56,237,255)",
fill: true,
}
],
options: {
...options
},
};
console.log(timeFormat)
return (
<div
className={styles.Chart}
{...props}
>
<Line id="myChart" data={chart} options={options} />
<div className="chart-button mt-1">
<Button
onClick={() => setTimeFormat("1")}
appearance={"primary"} >
24h
</Button>
<Button
onClick={() => setTimeFormat("7")}
appearance={"primary"}
>
7d
</Button>
<Button
onClick={() => setTimeFormat("30")}
appearance={"primary"}
>
30d
</Button>
</div>
</div>
);
};
I've been searching for it on a doc., but I haven't found this info.
And here below my options code:
export const options = {
plugins: {
// show legends for our graph
legend: {
display: false,
},
},
lineHeightAnnotation: {
always: true,
lineWeight: 3,
},
// animate in
animation: {
duration: 1,
},
// show the x and y scales
scales: {
x: {
display: true,
},
y: { display: true },
},
time: {
useUTC: true
},
xAxis: {
type: 'datetime'
},
};
Thanks in advance!:)
Okay here it is my ChartConfig.js
export const options = {
plugins: {
// show legends for our graph
legend: {
display: false,
},
},
lineHeightAnnotation: {
always: true,
lineWeight: 3,
},
// animate in
animation: {
duration: 1,
},
// show the x and y scales
scales: {
x: {
display: true,
ticks: {
maxRotation: 0, // this line to make labels horizontal
maxTicksLimit: 5, // this is num of labels limit
}
},
y: {
display: true
},
xAxes: [{
ticks: {
maxRotation: 90
}
}]
},
time: {
useUTC: true
},
};
And as a result:

Rfresh the parents component while updating in detailCellRendering in ag-grid

We have One parents componet Template in That i m using one detailsCellRendering componet for cellRedering in ag-grid..in the detailsCellRendering componet I am updating TextValue and after clicking on handleDoneValue event (done button ) the Template page should also refresh.But I am not able to do ...i need help like how can i update Template page while updating in DetailsCellRending Component.
class Template extends Component {
constructor(props) {
super(props);
this.state = {
columnDefs: [
{
headerName: "Channel Field",
field: "field",
filter: "agTextColumnFilter",
filterParams: {
buttons: ["reset"],
debounceMs: 1000,
suppressAndOrCondition: true, // it will remove AND/OR conditions
filterOptions: [
"contains",
"notContains",
"equals",
"notEqual",
"startsWith",
"endsWith"
]
},
cellRendererParams: {
prop1: "this is prop1"
},
cellRenderer: "agGroupCellRenderer",
},
{
headerName: "Mapping from Your Data",
field: "mapping_field",
filter: "agNumberColumnFilter",
},
{
headerName: skuValue,
field: "value",
},
{
headerName: "Status",
field: "status",
filter: 'agSetColumnFilter',
filterParams: {
values: function (params) {
// simulating async delay
setTimeout(function () {
params.success(["True", "False"]);
}, 500);
}
},
// cellRenderer: "ColourRender",
cellStyle: params => {
if (params.value === "Mapped") {
//mark mapped cells as green
return { color: 'green' };
} else {
return { color: 'red' };
}
}
},
{
headerName: "Required",
field: "required",
filter: "agSetColumnFilter",
cellRenderer: "BooleanRender",
filterParams: {
values: function (params) {
// simulating async delay
setTimeout(function () {
params.success(["True", "False"]);
}, 500);
}
}
},
],
columnDefsforSku: [
{
headerName: "Channel Field",
field: "field",
filter: "agTextColumnFilter",
filterParams: {
buttons: ["reset"],
debounceMs: 1000,
suppressAndOrCondition: true, // it will remove AND/OR conditions
filterOptions: [
"contains",
"notContains",
"equals",
"notEqual",
"startsWith",
"endsWith",
// "In List",
// "Not In List"
]
},
cellRenderer: "agGroupCellRenderer",
},
{
headerName: "Mapping from Your Data",
field: "mapping_field",
filter: "agNumberColumnFilter",
},
{
headerName: "Status",
field: "status",
filter: 'agSetColumnFilter',
filterParams: {
values: function (params) {
// simulating async delay
setTimeout(function () {
params.success(["True", "False"]);
}, 500);
}
},
cellStyle: params => {
if (params.value === "Mapped") {
//mark mapped cells as green
return { color: 'green' };
} else {
return { color: 'red' };
}
}
},
{
headerName: "Required",
field: "required",
filter: "agSetColumnFilter",
cellRenderer: "BooleanRender",
filterParams: {
values: function (params) {
// simulating async delay
setTimeout(function () {
params.success(["True", "False"]);
}, 500);
}
}
},
],
components: {
DetailCellRenderer: {DetailCellRenderer},
},
defaultColDef: {
flex: 1,
resizable: true,
// tooltipComponent: "customTooltip",
floatingFilter: true,
minWidth: 170,
sortable: true,
},
rowModelType: "serverSide",
frameworkComponents: {
customNoRowsOverlay: CustomNoRowsOverlay,
loadingRender: loadingRender,
myDetailCellRenderer: DetailCellRenderer,
customTooltip: CustomTooltip,
BooleanRender: BooleanRender,
// ColourRender: ColourRender,
},
context: { componentParent: this },
pagination: true,
serverSideStoreType: "full",
rowSelection: "multiple",
loadingCellRenderer: "loadingRender",
loadingCellRendererParams: { loadingMessage: "One moment please..." },
loadingOverlayComponent: "loadingRender",
totalProductsCount: 0,
catalogfilterCount: 0,
noRowsOverlayComponent: "customNoRowsOverlay",
noRowsOverlayComponentParams: {
noRowsMessageFunc: function () {
return "Please Select Product Preview"
}
},
getDetailRowData: function (params) {
// params.successCallback([]);
params.successCallback(params.data.callRecords);
},
sideBar: 'filters',
tooltipShowDelay: 0,
paginationPageSize: 100,
cacheBlockSize: 30,
filterStatus: false,
sweetAlert: "",
allSKu: [],
sku: localStorage.getItem("skuPreviewProduct"),
isProductPrevewSelected: false,
skuInputValue: "",
loading: false,
product_id: localStorage.getItem("products_ids") ? localStorage.getItem("products_ids") : null,
// loadingForDetails: localStorage.getItem("loadings")
};
<Grid item xs={10}>
<div
id="myGrid"
style={{
height: "90%",
width: "90%",
}}
className="ag-theme-alpine template"
>
<AgGridReact
columnDefs={this.state.product_id ? columnDefs : columnDefsforSku}
defaultColDef={defaultColDef}
onGridReady={this.onGridReady}
rowModelType={rowModelType}
masterDetail={true}
enableCellChangeFlash={true}
masterDetail={true}
detailCellRenderer={'myDetailCellRenderer'}
detailRowHeight={350}
height={400}
width={600}
animateRows={true}
frameworkComponents={frameworkComponents}
embedFullWidthRows={true}
loadingOverlayComponent={loadingOverlayComponent}
loadingCellRenderer={loadingCellRenderer} // default loading renderer
loadingCellRendererParams={loadingCellRendererParams} // renderer Params to load msg
noRowsOverlayComponent={noRowsOverlayComponent} // default no rows overlay component
noRowsOverlayComponentParams={noRowsOverlayComponentParams} // to show default no rows message
paginationPageSize={this.state.paginationPageSize} // pagination page size
onColumnVisible={this.onColumnVisible.bind(this)}
getDetailRowData={getDetailRowData}
cacheBlockSize={cacheBlockSize}
detailCellRendererParams={detailCellRendererParams }
/>
</div>
</Grid>
</Grid>
</div>
)
1. **List item**
}
// DetailsCellRendering page
import React, { useEffect, useState } from 'react';
import Paper from '#material-ui/core/Paper';
import Grid from '#material-ui/core/Grid';
import { makeStyles } from '#material-ui/core/styles';
import TemplateTab from "../views/FunctionalComponents/TemplateTab"
import { TEMPLATE_MARKETPLACE_FEILD_MAPPING, TEMPLATE_API } from "../configurations/configApi";
import { apiEdit, fetchUrl } from "../apiActions/action";
import LoadingOverlay from "../components/overlays/LoadingOverlay";
import Templates from 'views/Tables/Templates';
// import Template from 'views/Tables/Templates';
const useStyles = makeStyles(() => ({
root: {
flexGrow: 1,
textAlign: "center",
marginBottom: 20,
}
}));
const DetailCellRenderer = ({ data, params, api, node}) => {
const classes = useStyles();
const [allData, setAllData] = useState();
const [loading, setLoading] = useState(false);
const marketplaceId = localStorage.getItem("marketplaceId") ? localStorage.getItem("marketplaceId") : "" ;
const skuValue = localStorage.getItem("skuPreviewProduct") ? localStorage.getItem("skuPreviewProduct") : "";
const fetchAllTemplate = () => {
setLoading(true);
var soniServe = `${TEMPLATE_API}${marketplaceId}/?sku=${skuValue}&filter=${"[]"}`;
fetchUrl(soniServe, ({ status, response }) => {
if (status) {
let refreshValue = response.data.response[0].mappings.filter(item => data.id === item.id);
localStorage.setItem("cellRenderId", refreshValue && refreshValue[0]&& refreshValue[0].id )
setAllData(refreshValue && refreshValue[0])
setLoading(false)
} else {
if (response.response &&
response.response.status &&
((response.response.status === 401))
) {
localStorage.removeItem("token");
localStorage.removeItem("email");
window.location = "/auth/login-page";
}
}
});
}
useEffect(() => {
setAllData(data)
}, data)
// update text value
const handleDoneValue = (textValue) => {
const productId = allData && allData.id;
let value = textValue
// updating the existing labels
const urlForSave = `${TEMPLATE_MARKETPLACE_FEILD_MAPPING}${productId}/`;
const methodOfSave = "put";
const data = { "mappings": { "text_value": value } }
apiEdit(urlForSave, data, methodOfSave, ({ status, response }) => {
if (status) {
// window.location = `/configuration/details/${marketplaceId}`
fetchAllTemplate();
// inputMethod === "saveAs" && this.fetchProductDisplay("saveAs");
} else {
if (response.response &&
response.response.status &&
((response.response.status === 401))
) {
localStorage.removeItem("token");
localStorage.removeItem("email");
window.location = "/auth/login-page";
} else if (
(response &&
response.status &&
(response.status === 404 ||
response.status === 500)) ||
!response
) {
window.location = "/error";
} else {
// to show some popups
window.location = "/error";
}
}
});
}
return (
<div>
<div className={classes.root}>
<Grid container style={{ paddingTop: "10px" }}>
<Grid item xs={3}>
{allData && allData.field ? allData.field : null}
</Grid>
<Grid item xs={3}>
{ allData && allData.mapping_field ? allData.mapping_field : null}
</Grid>
<Grid item xs={3}>
{urlCheck && urlCheck[0] === "https" || urlCheck && urlCheck[0] === "http"? {allData && allData.value} : allData && allData.value ? allData.value : null}
{/* { data && data.value ? data.value : null} */}
</Grid>
<Grid item xs={3} >
{allData && allData.status}
</Grid>
</Grid>
</div>
<div className={classes.root}>
<Grid container spacing={1}>
<Grid item xs={4} justify="flex-end" style={{ display: "flex" }}>
Description
</Grid>
<Grid item xs={8} >
<Paper className="templateBox">
<span style={{ marginBottom: "20px" }}>What value should we send for each product's "{data.field}"? </span>
<TemplateTab allCellData={data} handleDoneValue={handleDoneValue}
/>
</Paper>
</Grid>
</Grid>
</div>
<LoadingOverlay showOverlay={loading} />
</div>
);
};
export default DetailCellRenderer;

How to import useCombinedRefs when using react-data-grid

I am trying to implement the draggable columns with react-data-grid based on this example: https://github.com/adazzle/react-data-grid/blob/canary/stories/demos/ColumnsReordering.tsx
I see that this example requires creating a DraggableHeaderRenderer file, so I have copied the following file into my project and converted it to React: https://github.com/adazzle/react-data-grid/blob/canary/stories/demos/components/HeaderRenderers/DraggableHeaderRenderer.tsx
My issue is that I do not know where to import useCombinedRefs from. It is not exported from react-data-grid. I see in the repo that it resides in src/hooks.
I have tried the following:
import {useCombinedRefs} from 'react-data-grid'
// Error: Attempted import error: 'useCombinedRefs' is not exported from 'react-data-grid'.
import {useCombinedRefs} from 'react-data-grid/lib/hooks';
// Error: Module not found: Can't resolve 'react-data-grid/lib/hooks' in 'C:\Users\Liam\Desktop\Work\MyProject\src\ReactDataGrid'
import useCombinedRefs from 'react-data-grid/lib/hooks/useCombinedRefs';
// Error: Module not found: Can't resolve 'react-data-grid/lib/hooks/useCombinedRefs' in 'C:\Users\Liam\Desktop\Work\MyProject\src\ReactDataGrid'
Thanks to anyone who can help.
Here is my code:
DraggableHeaderRenderer.js
import { useDrag, useDrop } from 'react-dnd';
import React from 'react'
import { SortableHeaderCell } from 'react-data-grid';
import useCombinedRefs from 'react-data-grid/lib/hooks/useCombinedRefs';
export function DraggableHeaderRenderer({ onColumnsReorder, column, sortColumn, sortDirection, onSort }) {
const [{ isDragging }, drag] = useDrag({
item: { key: column.key, type: 'COLUMN_DRAG' },
collect: monitor => ({
isDragging: !!monitor.isDragging()
})
});
const [{ isOver }, drop] = useDrop({
accept: 'COLUMN_DRAG',
drop({ key, type }) {
if (type === 'COLUMN_DRAG') {
onColumnsReorder(key, column.key);
}
},
collect: monitor => ({
isOver: !!monitor.isOver(),
canDrop: !!monitor.canDrop()
})
});
return (
<div
ref={useCombinedRefs(drag, drop)}
style={{
opacity: isDragging ? 0.5 : 1,
backgroundColor: isOver ? '#ececec' : 'inherit',
cursor: 'move'
}}
>
<SortableHeaderCell
column={column}
sortColumn={sortColumn}
sortDirection={sortDirection}
onSort={onSort}
>
{column.name}
</SortableHeaderCell>
</div>
);
}
TestDataGrid.js
import React from 'react';
import DataGrid from 'react-data-grid';
import {DraggableHeaderRenderer} from './DraggableHeaderRenderer';
import { useState, useCallback, useMemo } from 'react';
import 'react-data-grid/dist/react-data-grid.css';
const createRows = () => {
const rows = [];
for (let i = 1; i < 500; i++) {
rows.push({
id: i,
task: `Task ${i}`,
complete: Math.min(100, Math.round(Math.random() * 110)),
priority: ['Critical', 'High', 'Medium', 'Low'][Math.round(Math.random() * 3)],
issueType: ['Bug', 'Improvement', 'Epic', 'Story'][Math.round(Math.random() * 3)]
});
}
return rows;
}
const createColumns = () => {
return [
{
key: 'id',
name: 'ID',
width: 80,
},
{
key: 'task',
name: 'Title',
resizable: true,
sortable: true,
draggable: true
},
{
key: 'priority',
name: 'Priority',
resizable: true,
sortable: true,
draggable: true
},
{
key: 'issueType',
name: 'Issue Type',
resizable: true,
sortable: true,
draggable: true
},
{
key: 'complete',
name: '% Complete',
resizable: true,
sortable: true,
draggable: true
}
];
}
export default function TestDataGrid() {
const [rows] = useState(createRows)
const [columns, setColumns] = useState(createColumns)
const draggableColumns = useMemo(() => {
const HeaderRenderer = (props) => {
return <DraggableHeaderRenderer {...props} onColumnsReorder={handleColumnsReorder}/>
}
const handleColumnsReorder = (sourceKey, targetKey) => {
const sourceColumnIndex = columns.findIndex(c => c.key === sourceKey);
const targetColumnIndex = columns.findIndex(c => c.key === targetKey);
const reorderedColumns = [...columns];
reorderedColumns.splice(
targetColumnIndex,
0,
reorderedColumns.splice(sourceColumnIndex, 1)[0]
);
setColumns(reorderedColumns);
}
return columns.map(c => {
if(c.key === "id") return c;
return {...c, HeaderRenderer}
});
}, [columns])
return (
<DataGrid
columns={draggableColumns}
rows={rows}
/>
);
}

How to configure multiple bars on same chart using react-charts

I have a react wherein I am able to display the. For this i am using react-charts library.
To populate chart data I am making a API call and thereafter updating the state. I want to display multiple values for YAxis.
My sample API response is:
{
"result": 1,
"data": [
{
"data1": "1272.00",
"data2": "1183.00",
"price": "131.00"
},
{
"data1": "1328.00",
"data2": "1468.00",
"price": "132.00"
},
{
"data1": "1829.00",
"data2": "1445.00",
"price": "133.00"
},
]
}
I want data1 and data2 values forYAxis and price for XAxis.
React code:
import React, { Component } from "react";
import Sidebar from "./Sidebar";
import { Chart } from "react-charts";
import axios from "axios";
const qs = require("qs");
class Home extends Component {
state = {
datelist: [],
chart_data: []
};
componentDidMount() {
this.getDatesList();
axios
.post(
`http://127.0.0.1:8000/pricedata/`,
qs.stringify({ date: "2019-01-11" })
)
.then(res => {
if (res.data.result === 1) {
this.setState({
chart_data: [
{
label: "Strike",
data: res.data.data.map(Object.values)
}
]
});
} else {
this.setState({ chart_data: [] });
}
});
}
getDatesList() {
axios.get("http://127.0.0.1:8000/dateslist/").then(res => {
if (res.data.result === 1) {
this.setState({ datelist: res.data.data });
} else {
this.setState({ datelist: [] });
}
});
}
handleChange = event => {
var dateval = event.target.value;
axios
.post(`http://127.0.0.1:8000/pricedata/`, qs.stringify({ date: dateval }))
.then(res => {
if (res.data.result === 1) {
this.setState({
chart_data: [
{
label: "Strike",
data: res.data.data.map(Object.values)
}
]
});
} else {
this.setState({ chart_data: [] });
}
});
};
render() {
return (
<div className="container container_padding">
<div className="row">
<Sidebar />
<div className="col-md-9 col-sm-9 col-xs-12">
<select
className="form-control"
style={{ width: "120px", marginBottom: "10px" }}
onChange={this.handleChange}
>
{this.state.datelist.map((date, i) => (
<option value={date} key={i}>
{date}
</option>
))}
</select>
<div
style={{
width: "400px",
height: "300px"
}}
>
<Chart
data={this.state.chart_data}
series={{ type: "bar" }}
axes={[
{ primary: true, type: "ordinal", position: "bottom" },
{ type: "linear", position: "left", stacked: true }
]}
primaryCursor
tooltip
/>
</div>
</div>
</div>
</div>
);
}
}
export default Home;
How can I achieve this?
Thanks in advance.
Modify following lines:
handleChange = event => {
var dateval = event.target.value;
axios
.post(`http://127.0.0.1:8000/pricedata/`, qs.stringify({ date: dateval }))
.then(res => {
if (res.data.result === 1) {
this.setState({
chart_data: [
{
label: "bar1",
data: res.data.data.map((d) => ({ x: d.price, y: d.data1 })
},
{
label: "bar2",
data: res.data.data.map((d) => ({ x: d.price, y: d.data2 })
}
]
});
} else {
this.setState({ chart_data: [] });
}
});
};
and inside render:
<Chart
data={this.state.chart_data}
series={{ type: 'bar' }}
axes={[
{ primary: true, position: 'bottom', type: 'ordinal' },
{ position: 'left', type: 'linear', min: 0 },
]}
primaryCursor
secondaryCursor
tooltip
/>

Material ui v1 autocomplete - how to style it/ pass props to it?

Looking forward for any hint how to style new material ui v1 autocomplete or how to pass props to it.
Here's a codesandbox code (working example):
https://codesandbox.io/s/xrzq940854
In my particular case - I would like to style the label (which goes up after entering some value into input) and that horizontal line (underline under the input value).
Thank u for any help. (dropping code also in the snippet)
P.S. I got also a question how to pass props to the styles function. If anyone knows, please let me know :)
import React from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';
import match from 'autosuggest-highlight/match';
import parse from 'autosuggest-highlight/parse';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
import { MenuItem } from 'material-ui/Menu';
import { withStyles } from 'material-ui/styles';
const suggestions = [
{ label: 'Afghanistan' },
{ label: 'Aland Islands' },
{ label: 'Albania' },
{ label: 'Algeria' },
{ label: 'American Samoa' },
{ label: 'Andorra' },
{ label: 'Angola' },
{ label: 'Anguilla' },
{ label: 'Antarctica' },
{ label: 'Antigua and Barbuda' },
{ label: 'Argentina' },
{ label: 'Armenia' },
{ label: 'Aruba' },
{ label: 'Australia' },
{ label: 'Austria' },
{ label: 'Azerbaijan' },
{ label: 'Bahamas' },
{ label: 'Bahrain' },
{ label: 'Bangladesh' },
{ label: 'Barbados' },
{ label: 'Belarus' },
{ label: 'Belgium' },
{ label: 'Belize' },
{ label: 'Benin' },
{ label: 'Bermuda' },
{ label: 'Bhutan' },
{ label: 'Bolivia, Plurinational State of' },
{ label: 'Bonaire, Sint Eustatius and Saba' },
{ label: 'Bosnia and Herzegovina' },
{ label: 'Botswana' },
{ label: 'Bouvet Island' },
{ label: 'Brazil' },
{ label: 'British Indian Ocean Territory' },
{ label: 'Brunei Darussalam' },
];
function renderInput(inputProps) {
const { classes, autoFocus, value, ref, ...other } = inputProps;
return (
<TextField
autoFocus={autoFocus}
className={classes.textField}
value={value}
inputRef={ref}
label="Country"
InputProps={{
classes: {
input: classes.input,
},
...other,
}}
/>
);
}
function renderSuggestion(suggestion, { query, isHighlighted }) {
const matches = match(suggestion.label, query);
const parts = parse(suggestion.label, matches);
return (
<MenuItem selected={isHighlighted} component="div">
<div>
{parts.map((part, index) => {
return part.highlight ? (
<span key={String(index)} style={{ fontWeight: 300 }}>
{part.text}
</span>
) : (
<strong key={String(index)} style={{ fontWeight: 500 }}>
{part.text}
</strong>
);
})}
</div>
</MenuItem>
);
}
function renderSuggestionsContainer(options) {
const { containerProps, children } = options;
return (
<Paper {...containerProps} square>
{children}
</Paper>
);
}
function getSuggestionValue(suggestion) {
return suggestion.label;
}
function getSuggestions(value) {
const inputValue = value.trim().toLowerCase();
const inputLength = inputValue.length;
let count = 0;
return inputLength === 0
? []
: suggestions.filter(suggestion => {
const keep =
count < 5 && suggestion.label.toLowerCase().slice(0, inputLength) === inputValue;
if (keep) {
count += 1;
}
return keep;
});
}
const styles = theme => ({
container: {
flexGrow: 1,
position: 'relative',
height: 200,
},
suggestionsContainerOpen: {
position: 'absolute',
marginTop: theme.spacing.unit,
marginBottom: theme.spacing.unit * 3,
left: 0,
right: 0,
},
suggestion: {
display: 'block',
},
suggestionsList: {
margin: 0,
padding: 0,
listStyleType: 'none',
},
textField: {
width: '100%',
},
label: {
color: 'yellow',
}
});
class IntegrationAutosuggest extends React.Component {
state = {
value: '',
suggestions: [],
};
handleSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value),
});
};
handleSuggestionsClearRequested = () => {
this.setState({
suggestions: [],
});
};
handleChange = (event, { newValue }) => {
this.setState({
value: newValue,
});
};
render() {
const { classes } = this.props;
return (
<Autosuggest
theme={{
container: classes.container,
suggestionsContainerOpen: classes.suggestionsContainerOpen,
suggestionsList: classes.suggestionsList,
suggestion: classes.suggestion,
}}
renderInputComponent={renderInput}
suggestions={this.state.suggestions}
onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
renderSuggestionsContainer={renderSuggestionsContainer}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={{
autoFocus: true,
classes,
placeholder: 'Search a country (start with a)',
value: this.state.value,
onChange: this.handleChange,
}}
/>
);
}
}
IntegrationAutosuggest.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(IntegrationAutosuggest);
Material-UI v1 uses React-autosuggest module.
Check the below link
https://github.com/moroshko/react-autosuggest/blob/master/src/Autosuggest.js

Resources