I'm trying to use font-awesome in my reactjs application in material-table. I want to add a view button in every row inside my table. the code goes like this:-
const columns = [
{
title: "ID",
field: "id",
editable: false,
headerStyle: {
color: "white",
backgroundColor: "hwb(12deg 0% 0% / 86%)",
},
},
{
title: "Station Name",
field: "address.street",
headerStyle: {
color: "white",
backgroundColor: "hwb(12deg 0% 0% / 86%)",
},
},
{
title: "Location",
field: "address.city",
headerStyle: {
color: "white",
backgroundColor: "hwb(12deg 0% 0% / 86%)",
},
},
{
title: "Status",
field: "availibilityStatus",
headerStyle: {
color: "white",
backgroundColor: "hwb(12deg 0% 0% / 86%)",
},
},
{
title: " ",
field: "<FontAwesomeIcon icon="fa-solid fa-eye" />",
headerStyle: {
color: "white",
backgroundColor: "hwb(12deg 0% 0% / 86%)",
},
},
];
and I'm accessing it like this:-
<div className="App_wrapper">
<MaterialTable
title=" "
icons={tableIcons}
columns={columns}
data={data}
editable=
{{
onRowAdd: (newRow) =>
new Promise((resolve, reject) => {
len++;
const updatedRows = [...data, { id: len, ...newRow }];
setTimeout(() => {
setData(updatedRows);
resolve();
}, 20);
console.log(newRow);
}),
onRowDelete: (selectedRow) =>
new Promise((resolve, reject) => {
const index = selectedRow.tableData.id;
const updatedRows = [...data];
updatedRows.splice(index, 1);
setTimeout(() => {
setData(updatedRows);
console.log(selectedRow);
resolve();
}, 20);
}),
onRowUpdate: (updatedRow, oldRow) =>
new Promise((resolve, reject) => {
const index = oldRow.tableData.id;
const updatedRows = [...data];
updatedRows[index] = updatedRow;
console.log("updated row", updatedRow);
setTimeout(() => {
setData(updatedRows);
console.log(updatedRow);
resolve();
}, 20);
}),
onBulkUpdate: (selectedRows) =>
new Promise((resolve, reject) => {
const rows = Object.values(selectedRows);
const updatedRows = [...data];
let index;
rows.map((emp) => {
index = emp.oldData.tableData.id;
updatedRows[index] = emp.newData;
});
setData(updatedRows);
resolve();
}),
}}
options={{
actionsColumnIndex: -1,
addRowPosition: "first",
headerStyle: {
color: "white",
backgroundColor: "hwb(12deg 0% 0% / 86%)",
}
}}
// <PreviewIcon/>
/>
</div>
I know it's not the correct way, can some one pls help me get to know how I can do this?
my current web page looks something like this:-
Related
I'm working on apexcharts. I managed to pass data in chart, but there seem to be issue with timestamps. I have two data i.e sender and receiver, each has its own timestamps. the graph's x-axis is based on the timestamps. but I don't know how to map the timestamp with its respective data. currently, the data in the graph are not showing right due to the timestamp issue. kindly help me to fix it. thanks in advance
here's my full code
const receiverData = [];
const senderData = [];
const timeData = [];
export default function GraphCard() {
const [GraphData, setGraphData] = useState([])
const showData = () => {
axios.get('http://localhost:8006/api/v2/user/transactions').then(function (res) {
var result = res.data.data;
console.log(result)
if (result.data) {
setGraphData(result.data)
for (const obj of result.data) {
if (obj.role === 'Sender') {
receiverData.push(obj.tokens)
timeData.push(obj.date)
}
if (obj.role === 'Receiver') {
senderData.push(obj.tokens)
timeData.push(obj.date)
}
}
console.log("Reciever", receiverData)
console.log("Sender", senderData)
}
else {
console.log('error')
}
})
}
const state = {
series: [{
color: '#000073',
name: 'Received',
data: receiverData.map((data) => (data))
},
{
color: '#CA9026',
name: 'Sent',
data: senderData.map((data) => (data))
}],
options: {
chart: {
height: 280,
type: 'area'
},
dataLabels: {
enabled: false
},
stroke: {
curve: 'smooth'
},
xaxis: {
type: 'datetime',
categories: timeData.map((data) =>(data))
},
yaxis: {
type: ''
},
tooltip: {
x: {
format: 'dd/MM/yy HH:mm'
},
},
},
}
useEffect(() => {
showData()
}, [])
return (
<Card >
<CardContent display='flex' sx={{ flexDirection: 'column', }} >
<Stack flexDirection='row' alignItems="center" gap={1}>
< SsidChartOutlinedIcon sx={{ color: "text.secondary" }} />
<Typography sx={{ fontSize: 15, fontWeight: 'bold' }} color="text.secondary" gutterBottom>
Recent Transactions
</Typography>
</Stack>
<div id="chart">
<ReactApexChart options={state.options} series={state.series} type="area" height={280} />
</div>
</CardContent>
</Card>
);
}
On apex chart website, they have a case that is similar to yours:
series: [{
data: [{ x: '05/06/2014', y: 54 }, { x: '05/08/2014', y: 17 } , ... , { x: '05/28/2014', y: 26 }]
}]
apexchart docs
To achieve this kind of objects, you can just do this:
const showData = () => {
axios.get('http://localhost:8006/api/v2/user/transactions').then(function (res) {
var result = res.data.data;
console.log(result)
if (result.data) {
setGraphData(result.data)
for (const obj of result.data) {
if (obj.role === 'Sender') {
receiverData.push({x: obj.date.toString(), y: obj.tokens}) //date.toString() is not necessary if your date is already a string
timeData.push(obj.date)
}
if (obj.role === 'Receiver') {
senderData.push({x: obj.date.toString(), y: obj.tokens})
timeData.push(obj.date)
}
}
console.log("Reciever", receiverData)
console.log("Sender", senderData)
}
else {
console.log('error')
}
})
}
And the rest should not need to be changed.
I am trying to to make a MUI data table to be collapsible but I can't make it. So I have working demo of collapsible MUI table here https://codesandbox.io/s/19r60?file=/src/ExpandableRowTable.js
How can I transform the existing non collapsible MUI data table to collapsible MUI table?
Here is my code
TripsTable.js (minimal code)
function TripsTable({ data, userSettings, refetchData, ...props }) {
const classes = useStyles();
const { t } = useTranslation();
const isKm = userSettings.metrics === Metrics.KM;
const columns = [
{
field: "collision",
headerName: " ",
flex: 0.7,
disableColumnMenu: true,
renderCell: (params) => (
<span className={classes.iconsCell}>
{params.row.events
.map((e) => e.event_type_name)
.includes("COLLISION") && (
<img src={collision} alt="" title="Collision" />
)}
{params.row.isBeaconTagged && (
<img src={BeaconsIcon} alt="" title="Beacon" />
)}
{params.row.isBluetoothTagged && (
<img src={BluetoothIcon} alt="" title="Bluetooth" />
)}
</span>
),
},
{
field: "tripStartTimeStr",
headerName: t("date"),
flex: 1.5,
disableColumnMenu: true,
sortComparator: (v1, v2, p1, p2) => new Date(v1) - new Date(v2),
renderCell: (params) => (
<pre>
<span
style={{
marginLeft: 0,
padding: "5px 7px",
borderRadius: 7,
color: params.row.score < 72 ? "#fff" : "",
fontWeight: "normal",
backgroundColor:
params.row.score < 72 ? "#F44138" : "transparent",
}}
>
{params.value}
</span>
</pre>
),
},
{
field: "tripType",
headerName: t("tripType"),
flex: 1.4,
disableColumnMenu: true,
hide: isHiddenTripType,
renderCell: (params) => (
<TripTypeSelector
type={params.value}
tripId={params.row.tripId}
refetchTrips={refetchData}
/>
),
},
{
field: "drivingTimeSeconds",
headerName: t("drivingTime"),
flex: 1.1,
disableColumnMenu: true,
sortComparator: (v1, v2, p1, p2) =>
p1.api.getRow(p1.id).drivingTimeSeconds -
p2.api.getRow(p2.id).drivingTimeSeconds,
renderCell: (params) => (
<span>
{Math.round(params.value / 60)} {t("minutes")}
</span>
),
},
{
field: "distanceDriven",
headerName: t(isKm ? "kilometersDriven" : "milesDriven"),
flex: 1.1,
disableColumnMenu: true,
sortComparator: (v1, v2, p1, p2) =>
p1.api.getRow(p1.id).distanceDriven -
p2.api.getRow(p2.id).distanceDriven,
valueFormatter: (params) =>
`${params.value.toFixed(2)} ${t(isKm ? "km" : "mi")}`,
},
...DrivingBehaviourKeysArr.map((evnt) => ({
field: evnt,
headerName: t(evnt),
flex: 0.9,
disableColumnMenu: true,
renderCell: eventScoreCell,
})),
{
field: "fleetId",
headerName: t("Fleet"),
flex: 1.1,
disableColumnMenu: true,
},
{
field: "category",
headerName: t("category"),
flex: 1.1,
disableColumnMenu: true,
sortComparator: (v1, v2, param1, param2) =>
param1.api.getCellValue(param1.id, "score") -
param2.api.getCellValue(param2.id, "score"),
renderCell: (params) => (
<span style={{ color: getCategoryColor(params.row.score) }}>
{params.value}
</span>
),
},
{
field: "score",
headerName: t("score"),
flex: 1,
disableColumnMenu: true,
},
];
const [isVisible, setIsVisible] = useState(true);
const { fleetId, driverId } = useParams();
const { tripId } = useQuery();
const history = useHistory();
const ref = useRef();
const filteredData = isOnlyBusinessTrips
? data.filter((row) => row.tripType == TripTypes.BUSINESS)
: data;
const trip = useMemo(
() => filteredData.find((t) => t.tripId === tripId),
[filteredData, tripId]
);
useEffect(() => {
setTimeout(() => ref.current?.scrollIntoView({ behavior: "smooth" }), 100);
}, [isVisible, trip]);
const handleSelectTrip = useCallback(
(row) => {
if (row.id !== tripId) {
history.push(FrontendRoutes.DRIVER_OVERVIEW(fleetId, driverId, row.id));
setIsVisible(true);
} else {
setIsVisible(!isVisible);
}
},
[isVisible, driverId, tripId]
);
const rows = useMemo(
() => filteredData.map((d) => ({ ...d, id: d.tripId })),
[filteredData]
);
// console.log("data", data);
return (
<ChartWrapper {...props}>
<div className={classes.root}>
<DataTable
selectionModel={tripId ? [tripId] : undefined}
rows={rows}
columns={columns}
onCellClick={handleSelectTrip}
/>
</div>
{trip && isVisible && (
<DriverTripOverview trip={trip} userSettings={userSettings} />
)}
<span ref={ref} />
</ChartWrapper>
);
}
export default memo(TripsTable);
How can show DriverTripOverview component below every clicked table row?
I am getting error in my react App. I am using Material UI .
I get this error when I visit this page.
As per the error I am getting error in TablePagination, but I am not even using TablePagination component.
I am using Data Grid component of Material UI version 4. It has server-side pagination enabled and I am passsing in the number of rows as row count.(Below is the code.)
MiList component is using Data Grid.
import React, { useState, useEffect, useRef, memo } from "react";
import { MiButton, MiLink, MiList } from "../../../components/Standard/MiView";
import CreateNewPropertyModal from "./CreateNewPropertyModal";
import { THEME } from "../../../components/Standard/theme";
import { Chip } from "#miview/components";
import "./StyleTable.css";
import { debounce } from "../../../utils";
import { homeSearchHook } from "./utils";
import { formatDate } from "../../../helpers/dateTools";
import {
systemTypeService,
stageTypeService,
propertyService,
} from "#miview/api";
import { SYSTEM_TYPE_CATEGORIES } from "#miview/constants";
import { useComponentState } from "#miview/hooks";
import { MiTHEME } from "#miview/theme";
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles(() => ({
tableStyles: {
border: 0,
"& .MuiDataGrid-columnHeaderTitleContainer": {
padding: 0,
},
"& .MuiDataGrid-columnSeparator": {
visibility: "hidden",
},
},
}));
const Properties = memo((props) => {
const [newPropertyInProgress, setNewPropertyInProgress] = useState();
const [newOutlineInProgress, setNewOutlineInProgess] = useState();
const [stageTypes, setStageTypes] = useState([]);
const [garageSwingTypes, setGarageSwingTypes] = useState([]);
const [changed, setChanged] = useState(false);
const [sorted, setSorted] = useState([]);
const [addressInfo, setAddressInfo] = useState(null);
const [properties, setproperties] = useState([]);
const [pageNo, setpageNo] = useState(0);
const [pageSize, setpageSize] = useState(50);
const [rowCount, setrowCount] = useState(0);
const [searchTerm, setsearchTerm] = useState("");
// const [setupStatuses, setSetupStatuses] = useState([]);
const [homesMessage, getHomes] = homeSearchHook();
const [hasUserSearched, setHasUserSearched] = useState(false);
const debouncedSearchTerm = debounce(searchTerm, 300);
const isFirstRun = useRef(true);
const classes = useStyles();
const getColor = (val) => {
switch (val) {
case "Stage Complete":
return MiTHEME.colors.green.light;
case "Scheduled":
return MiTHEME.colors.blue.light;
case "Not Scheduled":
return MiTHEME.colors.bluegrey.light;
case "Not Ready":
return MiTHEME.colors.bluegrey.light;
default:
return MiTHEME.colors.blue.light;
}
};
const getTextColor = (val) => {
switch (val) {
case "Stage Complete":
return MiTHEME.colors.green.primary;
case "Scheduled":
return MiTHEME.colors.blue.primary;
case "Not Scheduled":
return MiTHEME.colors.bluegrey.primary;
case "Not Ready":
return MiTHEME.colors.bluegrey.primary;
default:
return MiTHEME.colors.blue.primary;
}
};
const stateManager = useComponentState();
useEffect(() => {
handleSearchHomes();
isFirstRun.current = false;
}, [debouncedSearchTerm]);
const handleSearchHomes = () => {
setHasUserSearched(!isFirstRun.current);
setpageNo(0);
filterData({
page: 0,
searchTerm: debouncedSearchTerm,
});
};
useEffect(() => {
// getSetupStatuses();
getStageTypes();
getGarageSwingTypes();
}, []);
// const getSetupStatuses = async () => {
// stateManager.run(async () => {
// const response = await propertyService.getSetupStatuses();
// setSetupStatuses(response);
// });
// };
const getStageTypes = async () => {
stateManager.run(async () => {
stageTypeService.getAll({}).then((response) => {
setStageTypes(response.filter((r) => r.stageOrder !== -1));
});
});
};
const getGarageSwingTypes = async () => {
stateManager.run(async () => {
const response = await systemTypeService.getSystemTypesByName({
name: SYSTEM_TYPE_CATEGORIES.GARAGE_SWING,
});
const mapped = response.map((i, k) => {
return { value: i.systemTypeId, key: k, text: i.mainValue };
});
setGarageSwingTypes(mapped);
});
};
useEffect(() => {
if (!changed && stageTypes.length > 0) {
let stageTypesToChange = stageTypes;
stageTypesToChange.push({ stageTypeName: "No Stage" });
setStageTypes(stageTypesToChange);
setChanged(true);
}
}, [stageTypes]);
// const getPropertySetupStatusFromCustomFields = (customFieldsJson) => {
// if (!customFieldsJson) return false;
// const fields = JSON.parse(customFieldsJson);
// const propertySetupStatuses = fields.find(
// (f) => f.name === "PropertySetupStatus"
// )?.value;
// const statusReducer = (a, s) =>
// a &&
// propertySetupStatuses.filter((ps) => ps.id == s.statusId && ps.value)
// .length > 0;
// return setupStatuses.reduce(statusReducer, true);
// };
const filterData = (params = {}) => {
stateManager.run(async () => {
getHomes(
params.page !== undefined ? params.page : pageNo,
params.pageSize || pageSize,
params.sorted || sorted,
params.searchTerm || searchTerm,
isFirstRun.current,
setpageNo,
setpageSize,
setrowCount,
setproperties
);
});
};
const toggleModal = () => {
setNewPropertyInProgress(!newPropertyInProgress);
};
const headerContent = (
<MiButton
title="Home"
icon="add"
inverse={true}
onClick={toggleModal}
color={THEME.GREEN_PRIMARY}
/>
);
const renderHeader = ({ colDef }) => {
return (
<div
style={{
color: MiTHEME.colors.blue.primary,
fontWeight: MiTHEME.fontWeight.bold,
}}
>
{colDef.headerName}
</div>
);
};
const columns = [
{
field: "addressLine1",
headerName: "Address",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 1,
renderCell: (p) => {
return (
<MiLink
to={"/homes/" + p.propertyId}
title={p.value}
style={{ marginLeft: -8 }}
/>
);
},
},
{
field: "cityName",
headerName: "City",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 0.7,
},
{
field: "state",
headerName: "State",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 0.6,
},
{
field: "community",
headerName: "Community",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 1,
},
{
field: "builder",
headerName: "Builder",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 1,
},
{
field: "currentStage",
headerName: "Stage",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 0.8,
renderCell: (p) => {
return (
<MiLink
to={"/stages/" + p.currentStageId}
title={p.value}
style={{ marginLeft: -8 }}
/>
);
},
},
{
field: "currentStageScheduledDate",
headerName: "Schedule Date",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 1,
valueFormatter: (params) => {
return formatDate(params.value);
},
},
{
field: "propertyStatus",
headerName: "Status",
width: 150,
renderHeader: renderHeader,
headerAlign: "left",
align: "left",
flex: 1,
renderCell: ({ value }) => {
return (
<Chip
text={value}
style={{
display: "flex",
borderRadius: "30px",
height: "30px",
minWidth: "80px",
justifyContent: "center",
padding:'0 7px 0 7px'
}}
color={getColor(value)}
textColor={getTextColor(value)}
/>
);
},
},
];
const toggleOutliner = () => {
setNewOutlineInProgess(!newOutlineInProgress);
};
useEffect(() => {
if (addressInfo) {
toggleOutliner();
}
}, [addressInfo]);
const modals = [
newPropertyInProgress ? (
<CreateNewPropertyModal
key={0}
getAddressInfo={setAddressInfo}
toggle={toggleModal}
stageTypes={stageTypes}
garageSwingTypes={garageSwingTypes}
history={props.history}
></CreateNewPropertyModal>
) : (
""
),
];
return (
<>
{stateManager.statusTag("propertyListStatus")}
<MiList
data={properties}
headerTitle={`Homes - ${hasUserSearched ? "All" : "Recent"}`}
headerIcon={"home"}
className={classes.tableStyles}
getRowId={(row) => row.propertyId}
headerContent={headerContent}
modals={modals}
callouts={null}
columns={columns}
manual
defaultPageSize={50}
pages={rowCount}
fetchData={isFirstRun.current ? () => null : filterData}
setSearch={setsearchTerm}
disableSearchButton
searchMessage={homesMessage}
disableColumnMenu
hideFilters
mui
/>
</>
);
});
export default Properties;
I found the same error. but I am using the table for showing details and also using with it to change the table pages. Here, if I pass just count={orders.data.total} I am facing the error. But when I am setting a default value 0 or any number then it is fixed.
someting like count={orders.data.total || 0}
<TablePagination
className={classes.tablePagination}
rowsPerPageOptions={[10, 25, 50, 100]}
component="div"
count={orders?.data?.total || 0}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
I'm trying to scale a slice of this Victory Pie chart on mouse hover but I'm having a difficult time getting it to render correctly. Has anyone had any luck with this? I've tried adding things like transform: scale(1.2) to the mutation style but it moves the slice rather than scales (I believe this is because scale scales based on the point of (0,0)). I've also tried playing around with translate or matrix but I can't get it to work correctly. Here's my code:
<div style={{ width: '150px' }}>
<VictoryPie
data={[
{ x: 'Cats', y: 35, label: 'Cats \n 35%' },
{ x: 'Dogs', y: 40, label: 'Dogs \n 40%' },
{ x: 'Birds', y: 55, label: 'Birds \n 55%' }
]}
labelComponent={
<VictoryTooltip
cornerRadius={10}
pointerWidth={30}
pointerLength={20}
flyoutPadding={{ top: 10, bottom: 10, left: 25, right: 25 }}
style={{ fontSize: '36px', fill: '#FFF' }}
flyoutStyle={{ fill: '#414B5F' }}
orientation="right"
/>
}
colorScale={['tomato', 'orange', 'gold', 'cyan', 'navy']}
innerRadius={100}
events={[
{
target: 'data',
eventHandlers: {
onMouseOver: () => {
return [
{
target: 'data',
mutation: () => ({ style: { fill: 'red', width: 30 } })
},
{
target: 'labels',
mutation: () => ({ active: true })
}
]
},
onMouseOut: () => {
return [
{
target: 'data',
mutation: () => {}
},
{
target: 'labels',
mutation: () => ({ active: false })
}
]
}
}
}
]}
/>
</div>
I added a simple mutation that changes the slice to red on hover and that works great. I'm just having a difficult time finding the best way to make the slice scale up slightly without causing problems.
Thanks in advance
You can use a custom component to render slices
const CustomSlice = (props) => {
const [scale, setScale] = useState(1);
// modified transformation from here
// https://github.com/FormidableLabs/victory/blob/844109cfe4e40b23a4dcb565e551a5a98015d0c0/packages/victory-pie/src/slice.js#L74
const transform = `translate(${props.origin.x}, ${props.origin.y}) scale(${scale})`;
return (
<Slice
{...props}
style={{ ...props.style }}
events={{
onMouseOver: (e) => {
if (props.events.onMouseOver) {
props.events.onMouseOver(e);
}
setScale((c) => c * 1.2);
},
onMouseOut: (e) => {
if (props.events.onMouseOut) {
props.events.onMouseOut(e);
}
setScale(1);
}
}}
transform={transform}
/>
);
};
<div style={{ width: "150px" }}>
<VictoryPie
dataComponent={<CustomSlice />}
data={[
{ x: "Cats", y: 35, label: "Cats \n 35%" },
{ x: "Dogs", y: 40, label: "Dogs \n 40%" },
{ x: "Birds", y: 55, label: "Birds \n 55%" }
]}
labelComponent={
<VictoryTooltip
cornerRadius={10}
pointerWidth={30}
pointerLength={20}
flyoutPadding={{ top: 10, bottom: 10, left: 25, right: 25 }}
style={{ fontSize: "36px", fill: "#FFF" }}
flyoutStyle={{ fill: "#414B5F" }}
orientation="right"
/>
}
colorScale={["tomato", "orange", "gold", "cyan", "navy"]}
innerRadius={100}
events={[
{
target: "data",
eventHandlers: {
onMouseOver: (e) => {
return [
{
target: "data",
mutation: () => ({
style: { fill: "red", width: 30 }
})
},
{
target: "labels",
mutation: () => ({ active: true })
}
];
},
onMouseOut: () => {
return [
{
target: "data",
mutation: () => {}
},
{
target: "labels",
mutation: () => ({ active: false })
}
];
}
}
}
]}
/>
</div>
I tried everything written in this previous question, the problem is that the select dropdown is behind the other input field called "select..." which is also coming from another library: react-modern-calendar-date-picker. Not sure why does not work, I also tried to create another css page and add to the select a custom class but did not work either. This is my code so far:
import { useContext, useEffect, useState } from 'react';
// styled components
import styled from 'styled-components';
// select input
import Select, { NonceProvider } from 'react-select';
import { Context } from '../../../Context/Context';
const FirstContext = ({ text, options, contextId, selected, value, index }) => {
const [treeNodeNames, setTreeNodeNames] = useState([]);
const [context, setContext] = useState();
const { setContexts, setMandatoryContext } = useContext(Context);
console.log('value first context', value);
useEffect(() => {
setContext(value);
}, [value]);
useEffect(() => {
if (context) {
setContexts((prev) => [
...prev.filter((el) => el.name !== text),
context,
]);
}
}, [context]);
useEffect(() => {
if (index === 0 && context) {
setMandatoryContext(context);
}
}, [context]);
// console.log("clean - state",context)
// clean one context when selected change
useEffect(() => {
if (treeNodeNames[0]) {
console.log('Ordre marco', context);
}
}, [treeNodeNames, context]);
useEffect(() => {
setContext(undefined);
}, [selected]);
// const options = [
// { value: 'chocolate', label: 'Chocolate' },
// { value: 'strawberry', label: 'Strawberry' },
// { value: 'vanilla', label: 'Vanilla' },
// ];
// THIS IS FROM THE LIBRARY
const customStyles = {
option: (provided, state) => {
// console.log("state", state);
return {
...provided,
borderBottom: '1px solid #f8f8f8',
color: 'black',
backgroundColor: 'white',
'&:hover': {
backgroundColor: '#f8f8f8',
color: 'black',
},
menuPortal: (provided) => ({ ...provided, zIndex: 9999 }),
menu: (provided) => ({ ...provided, zIndex: 9999 }),
// textAlign: 'right',
};
},
control: (styles) => ({
...styles,
'&:hover': {
border: '1px solid rgba(18, 18, 18, 0.3)',
// border: 'none',
},
// border: 'none',
border: '1px solid rgba(18, 18, 18, 0.1)',
boxShadow: 'none',
// textAlign: 'right',
padding: '10px',
borderRadius: '10px',
}),
singleValue: (provided, state) => {
const opacity = state.isDisabled ? 0.5 : 1;
const transition = 'opacity 300ms';
return { ...provided, opacity, transition };
},
placeholder: (provided) => {
return { ...provided };
// return { position: 'absolute', right: 5 };
},
indicatorSeparator: (provided) => {
return {
indicatorSeparator: null,
};
},
dropdownIndicator: (provided) => {
return {
...provided,
color: '#46AA8A',
'&:hover': {
color: 'rgba(20, 97, 101, 255)',
},
};
},
input: (provided) => {
return {
...provided,
};
},
};
useEffect(() => {
if (options) {
const treeNodes = options.data.findTreeNodesByTree.map((element) => {
return {
name: text,
value: element.name,
label: element.name,
id: element._id,
selection: element._id,
context: contextId,
custom: null,
};
});
setTreeNodeNames(treeNodes);
}
}, [options]);
console.log('individual context', context);
return (
<ContextContainer>
<ContextTitle>
<p>{text}</p>
</ContextTitle>
{treeNodeNames && (
<SearchInput>
<Select
onChange={
index === 0 ? (e) => setMandatoryContext(e) : (e) => setContext(e)
}
placeholder="Select"
value={value || context}
options={treeNodeNames}
styles={customStyles}
isSearchable
isClearable
/>
</SearchInput>
)}
</ContextContainer>
);
};
// STYLES
const ContextContainer = styled.div`
display: flex;
margin-left: auto;
/* flex-direction: column; */
align-items: center;
justify-content: space-between;
/* text-align: end; */
/* border-bottom: 0.5px solid #d8d8d8; */
`;
const ContextTitle = styled.div`
display: flex;
/* width: 75%; */
align-items: center;
justify-content: space-between;
`;
const SearchInput = styled.div`
width: 30vw;
padding: 10px 0px 10px 20px;
outline: black;
margin-right: 40px;
`;
export default FirstContext;
Try setting zIndex directly in menu rather nesting it inside option
const customStyles = {
option: (provided, state) => {
// console.log("state", state);
return {
...provided,
borderBottom: '1px solid #f8f8f8',
color: 'black',
backgroundColor: 'white',
'&:hover': {
backgroundColor: '#f8f8f8',
color: 'black',
}
};
},
menu: (provided, state) => {
return {
...provided,
zIndex: 9999
}
}