I have the below component as the main layout. When I click on the menu item, I want them to navigate to the home, holiday calendar, and event pages. What can I do with this horizontal menu? The below code shows the main layout wrapped around the above pages. I am using AntD and react-router. this main layout is wrapped around all other routers.
import { Layout, Menu, Button, Avatar, Row, Col, Space, Dropdown } from "antd";
import React, { useState } from "react";
import { Outlet } from "react-router-dom";
const navigation = [
{ label: "Home", key: 1 },
{ label: "Holiday Calendar", key: 2 },
{ label: "Event", key: 3 },
];
const MainLayout = () => {
const [open, setOpen] = useState(false);
const showDrawer = () => {
setOpen(true);
};
const onClose = () => {
setOpen(false);
window.dispatchEvent(new Event("loadHolidayCalander"));
};
const handleLogOut = () => {
localStorage.removeItem("access-token");
};
const menu = (
<Menu
items={[
{
key: "1",
label: <Button onClick={handleLogOut}>Log out</Button>,
},
]}
></Menu>
);
return (
<Layout style={{backgroundColor:"white"}}>
<Row style={{ backgroundColor:"#404140"}}>
<Col
style={{padding:5, margin:0, height:48}}
flex="300px"
>
<a href="/holiday-calander">
<img src="/logo.png" alt="logo" style={{ height: 38 }} />
</a>
</Col>
<Col>
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={["2"]}
items={navigation}
/>
</Col>
<Col
flex="auto"
style={{
padding:5
}}
>
<div style={{ position: "absolute", right: "5px" }}>
<Space size={20}>
<Dropdown overlay={menu} placement="topRight" arrow>
<Avatar style={{ width: 38, height:38 }} />
</Dropdown>
</Space>
</div>
</Col>
</Row>
<Layout
style={{
padding: 0,
backgroundColor: "white",
marginLeft:28,
marginRight:28,
}}
>
<Outlet />
</Layout>
</Layout>
);
};
export default MainLayout;
You can add an onClick handler to the Menu component, which will be passed an object with the key property you can search the navigation array for the matching element.
Add a link target to the navigation array elements.
import { ..., useNavigate, ... } from 'react-router-dom';
...
const navigation = [
{ label: "Home", key: 1, target: "/" },
{ label: "Holiday Calendar", key: 2, "/holidaycalendar" },
{ label: "Event", key: 3, "/event" },
];
...
const navigate = useNavigate();
const handleMenuClick = ({ key }) => {
const { target } = navigation.find(item => item.key === key) || {};
if (target) {
navigate(target);
}
};
...
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={["2"]}
items={navigation}
onClick={handleMenuClick}
/>
An improvement could be to make the key property the link target.
import { ..., useNavigate, ... } from 'react-router-dom';
...
const navigation = [
{ label: "Home", key: "/" },
{ label: "Holiday Calendar", key: "/holidaycalendar" },
{ label: "Event", key: "/event" },
];
...
const navigate = useNavigate();
const handleMenuClick = ({ key }) => {
if (key) {
navigate(key);
}
};
...
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={["/holidaycalendar"]}
items={navigation}
onClick={handleMenuClick}
/>
Related
as far as now my code is working fine : The tab indicator is moving accordingly to the url of my tab.
But there's a strange behaviour happening when the back button of the browser is getting pressed, the url is changing but the indicator stay on the same tab as before.
Here's the code :
import * as React from 'react';
import { Tabs, Tab, Box } from '#mui/material';
import { useNavigate } from 'react-router-dom';
import { HOME_PAGE } from '../../../router/customRouter';
const navigationsListTabs = [
{
id: 0,
path: '/dev',
label: 'Dev',
isDisable: false,
},
{
id: 1,
path: '/images',
label: 'Images',
isDisable: false,
},
{
id: 2,
path: '/services',
label: 'Services',
isDisable: false,
},
{
id: 3,
path: '/users',
label: 'users',
isDisable: true,
},
];
export const Header = () => {
const [value, setValue] = React.useState(0);
const navigate = useNavigate();
React.useEffect(() => {
navigate('/dev');
}, []);
function handleChange(event, newValue) {
const selectedTab = navigationsListTabs.find((tab) => tab.id === newValue);
navigate(HOME_PAGE + selectedTab.path);
setValue(newValue);
}
return (
<Box sx={{ width: '100%' }}>
<Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
<Tabs
value={value}
onChange={handleChange}
data-testid="tabs-menu-component"
>
{navigationsListTabs.map((item) => (
<Tab
key={item.id}
value={item.id}
label={item.label}
aria-label={item.label}
disabled={item.isDisable}
/>
))}
</Tabs>
</Box>
</Box>
);
};
Tried so far :
Using multiple conditions comparing url (not working) :
let url = window.location.pathname;
console.log(url);
const valueGetter = () => {
if (url.includes('dev')) {
return 0;
} else if (url.includes('images')) {
return 1;
} else if (url.includes('services')) {
return 2;
} else {
return 3;
}
};
console.log(valueGetter());
const [value, setValue] = React.useState(valueGetter);
Thanks to anyone who can help :)
If value is fully dependent on path, perhaps consider to always get value from pathname, instead of saving it as a state and handle both.
This example handles pathname with useLocation, so it gets updated by the hook when path changes. value is generated based on pathname.
Example:
import * as React from "react";
import { Tabs, Tab, Box } from "#mui/material";
import { useNavigate, useLocation } from "react-router-dom";
import { HOME_PAGE } from "../../../router/customRouter";
const navigationsListTabs = [
{
id: 0,
path: "/dev",
label: "Dev",
isDisable: false,
},
{
id: 1,
path: "/images",
label: "Images",
isDisable: false,
},
{
id: 2,
path: "/services",
label: "Services",
isDisable: false,
},
{
id: 3,
path: "/users",
label: "users",
isDisable: true,
},
];
export const Header = () => {
const navigate = useNavigate();
// 👇 Get value from pathname instead of saving it as state
const { pathname } = useLocation();
const currentTab = navigationsListTabs.find(
(tab) => tab.path === `/${pathname.split("/")?.pop()}`
);
const value = currentTab ? currentTab?.id : 0;
React.useEffect(() => {
navigate("/dev");
}, []);
function handleChange(event, newValue) {
const selectedTab = navigationsListTabs.find((tab) => tab.id === newValue);
navigate(HOME_PAGE + selectedTab.path);
}
return (
<Box sx={{ width: "100%" }}>
<Box sx={{ borderBottom: 1, borderColor: "divider" }}>
<Tabs
value={value}
onChange={handleChange}
data-testid="tabs-menu-component"
>
{navigationsListTabs.map((item) => (
<Tab
key={item.id}
value={item.id}
label={item.label}
aria-label={item.label}
disabled={item.isDisable}
/>
))}
</Tabs>
</Box>
</Box>
);
};
I am pretty new to React js and trying different ways to make a to-do list to understand it further. I have a parent component that renders two child components. I figured out how to transfer the items between the two lists. How do I add items to the 2 lists separately from the UI? I am not able to figure that out. I need two input textboxes for each list and also should be able to edit the list items. Can anybody please help me?
import React,{useState,useEffect} from 'react'
import { Completed } from './Completed'
import { Pending } from './Pending'
export const Items = () => {
const [items,setItems]=useState([
{
id: 1,
title:'Workout',
status:'Pending'
},
{
id: 2,
title:'Read Books',
status:'Pending'
},
{
id: 3,
title:'Cook Pizza',
status:'Pending'
},
{
id: 4,
title:'Pay Bills',
status:'Completed'
},
{
id: 5,
title:' Watch Big Short',
status:'Completed'
},
{
id: 6,
title:' Make nutrition Plan',
status:'Pending'
}
])
const updateStatus=(id,newStatus)=>{
let allItems=items;
allItems=allItems.map(item=>{
if(item.id===id){
console.log('in here')
item.status=newStatus;
}
return item
})
setItems(allItems)
}
return (
<div class="items">
<Pending items={items} setItems={setItems} updateStatus={updateStatus}/>
<Completed items={items} setItems={setItems} updateStatus={updateStatus}/>
</div>
)
}
import React from 'react'
export const Completed = ({items,setItems,updateStatus}) => {
return (
<div className="completed">
<h1>RIGHT</h1>
{
items && items.map(item=>{
if(item && item.status==='Completed')
return <><p className="item" key={item.id}>{item.title} <button className="mark_pending" key={item.id} onClick={()=>{updateStatus(item.id,'Pending')}}> Move Left</button></p></>
})
}
</div>
)
}
import React from 'react'
export const Pending = ({items,setItems,updateStatus}) => {
return (
<div className="pending">
<h1>LEFT</h1>
{
items && items.map(item=>{
if(item && item.status==='Pending')
return <><p className="item" key={item.id}>{item.title} <button className="mark_complete" key={item.id} onClick={()=>{updateStatus(item.id,'Completed')}}>Move Right</button></p></>
})
}
</div>
)
}
What do you mean by "separately from the UI" ?
import React, { useState } from "react";
const initialStatus = "Pending";
const initialData = [
{
id: 1,
title: "Workout",
status: "Pending",
},
{
id: 2,
title: "Read Books",
status: "Pending",
},
{
id: 3,
title: "Cook Pizza",
status: "Pending",
},
{
id: 4,
title: "Pay Bills",
status: "Completed",
},
{
id: 5,
title: " Watch Big Short",
status: "Completed",
},
{
id: 6,
title: " Make nutrition Plan",
status: "Pending",
},
];
const Box = ({ id, title, status, setItems, items }) => {
return (
<button
onClick={() => {
const newItems = [...items];
const index = items.findIndex((v) => v.id == id);
newItems[index].status =
newItems[index].status == initialStatus ? "Completed" : initialStatus;
setItems(newItems);
}}
>
{title}
</button>
);
};
export const Items = () => {
const [items, setItems] = useState(initialData);
return (
<div style={{ display: "flex" }}>
<div style={{ display: "flex", flexDirection: "column" }}>
<h1>LEFT</h1>
{items
.filter((v) => v.status === initialStatus)
.map((props) => (
<Box {...props} key={props.id} setItems={setItems} items={items} />
))}
</div>
<div style={{ display: "flex", flexDirection: "column" }}>
<h1>Right</h1>
{items
.filter((v) => v.status !== initialStatus)
.map((props) => (
<Box {...props} key={props.id} setItems={setItems} items={items} />
))}
</div>
</div>
);
};
export default Items;
I am displaying list item through map function. But I want the list item to automatically trigger itself and show something for instance i am just using console.log for that. So the first list item should automatically trigger it's onClick function. Is there anyway to acheive this in react?
...
import React, { useState } from "react";
import ListGroup from "react-bootstrap/ListGroup";
import Container from "react-bootstrap/Container";
import Button from "react-bootstrap/Button";
import "./App.css";
const App = () => {
const [data, useData] = useState([
{ list: "appelllll" },
{ list: "ballllslsss" },
{ list: "cattsssssss" },
{ list: "dogssssss" },
{ list: "eggssss" },
{ list: "fatssssssssssssssssssss" },
{ list: "goatssssssssssssssss" },
{ list: "heloooooooooooooooooo" },
{ list: "ieloooooooooooooo" },
{ list: "jelooooooooo" },
{ list: "kelooooooo" },
{ list: "leooo" },
{ list: "melosdsadsado" }
]);
return (
<Container className="p-3">
<ListGroup
className="list_menu"
horizontal
style={{
overflowX: "scroll"
}}
>
<button>+</button>
{data.map((data, i) => {
return (
<div>
<ListGroup.Item
className="list_item"
key={i}
onClick={() => console.log(data)}
>
{data.list}
</ListGroup.Item>
</div>
);
})}
<button> > </button>
</ListGroup>
</Container>
);
};
export default App;
...
working code here https://codesandbox.io/s/vigorous-rgb-koiwf?file=/src/App.js
I think it's better to do it like this:
onClick={() => {
if(i === 0)
console.log(data)
}}
I have 2 libs for my navigation. React navigation v5 and react-native-tab-view. 3 tabs from react navigation : Home/Discover/Profile. Discover is a screen with react native tab view. I have few buttons in Home, after press them they should navigate me to Discover tab and specific tab in Tab View. For now, I made the navigation from Home to Discover with react navigation. But how can i jump to a specific tab after i navigate to Discover?
This is sone element in Home which holds the button that will navigate me from Home to Discover:
render() {
const { error, pending, refresh, videos } = this.props;
return (
<HomeViewItem
headerText={'Top Videos'}
footerText={'More Videos'}
navigate={() =>
this.props.navigation.navigate('TabNavigator', {
screen: 'Discover',
}) // this will navigate me to Discover
}
view={this._renderVideos(videos, pending, error, refresh)}
/>
);
}
this is tab view in Discover screen:
export default class DiscoverTabView extends React.Component<DiscoverProps> {
_StreamsRoute = () => <StreamsTabScreen navigation={this.props.navigation} />;
_NewsRoute = () => <NewsTabScreen navigation={this.props.navigation} />;
_VideosRoute = () => <VideosTabScreen navigation={this.props.navigation} />;
_RedditRoute = () => <RedditTabScreen navigation={this.props.navigation} />;
_PicturesRoute = () => (
<PicturesTabScreen navigation={this.props.navigation} />
);
state = {
index: 0,
routes: [
{ key: 'streams', title: 'Streams' },
{ key: 'news', title: 'News' },
{ key: 'videos', title: 'Videos' },
{ key: 'reddit', title: 'Reddit' },
{ key: 'pictures', title: 'Pictures' },
],
};
_handleIndexChange = (index: number) => this.setState({ index });
componentWillUpdate() {}
render() {
const renderTabBar = (
props: SceneRendererProps & { navigationState: State }
) => (
<TabBar
{...props}
indicatorStyle={{ bottom: 6 }}
style={{ backgroundColor: '#0C2B33', elevation: 0, shadowOpacity: 0 }}
scrollEnabled={true}
renderLabel={renderLabel}
renderIndicator={renderIndicator}
tabStyle={{ width: 87, height: 44 }}
/>
);
const renderLabel = ({
route,
focused,
color,
}: {
route: Route;
focused: boolean;
color: String;
}) => {
return (
<View style={{ width: 87, height: 44 }}>
<Text style={focused ? styles.active : styles.inactive}>
{route.title}
</Text>
<Image
source={
route.key === this.state.routes[this.state.routes.length - 1].key
? null
: images.tabViewSeparator
}
style={{ position: 'absolute', alignSelf: 'flex-end', top: 10 }}
/>
<Image
source={
focused ? images.tabViewIconActive : images.tabViewIconInactive
}
style={{
width: 20,
height: 20,
alignSelf: 'center',
position: 'absolute',
top: 21,
}}
/>
</View>
);
};
return (
<TabView
lazy={false}
navigationState={this.state}
renderScene={SceneMap({
streams: this._StreamsRoute,
news: this._NewsRoute,
videos: this._VideosRoute,
reddit: this._RedditRoute,
pictures: this._PicturesRoute,
})}
renderTabBar={renderTabBar}
onIndexChange={this._handleIndexChange}
initialLayout={{ width: Dimensions.get('window').width }}
/>
);
}
}
You do it by using a specific tab action: jumpTo.
The function goes as follows:
import { TabActions } from '#react-navigation/native';
const jumpToAction = TabActions.jumpTo("TabName", { params });
navigation.dispatch(jumpToAction);
Anyone know how to change the fontSize of the TableHeaderRow in a DevExtreme React Grid?
Here's an example of code from the website (https://devexpress.github.io/devextreme-reactive/react/grid/demos/featured/data-editing/) that I have been working with
import * as React from 'react';
import {
SortingState, EditingState, PagingState,
IntegratedPaging, IntegratedSorting,
} from '#devexpress/dx-react-grid';
import {
Grid,
Table, TableHeaderRow, TableEditRow, TableEditColumn,
PagingPanel, DragDropProvider, TableColumnReordering,
} from '#devexpress/dx-react-grid-material-ui';
import Paper from '#material-ui/core/Paper';
import Dialog from '#material-ui/core/Dialog';
import DialogActions from '#material-ui/core/DialogActions';
import DialogContent from '#material-ui/core/DialogContent';
import DialogContentText from '#material-ui/core/DialogContentText';
import DialogTitle from '#material-ui/core/DialogTitle';
import Button from '#material-ui/core/Button';
import IconButton from '#material-ui/core/IconButton';
import Input from '#material-ui/core/Input';
import Select from '#material-ui/core/Select';
import MenuItem from '#material-ui/core/MenuItem';
import TableCell from '#material-ui/core/TableCell';
import DeleteIcon from '#material-ui/icons/Delete';
import EditIcon from '#material-ui/icons/Edit';
import SaveIcon from '#material-ui/icons/Save';
import CancelIcon from '#material-ui/icons/Cancel';
import { withStyles } from '#material-ui/core/styles';
import { ProgressBarCell } from '../../../theme-sources/material-ui/components/progress-bar-cell';
import { HighlightedCell } from '../../../theme-sources/material-ui/components/highlighted-cell';
import { CurrencyTypeProvider } from '../../../theme-sources/material-ui/components/currency-type-provider';
import { PercentTypeProvider } from '../../../theme-sources/material-ui/components/percent-type-provider';
import {
generateRows,
globalSalesValues,
} from '../../../demo-data/generator';
const styles = theme => ({
lookupEditCell: {
paddingTop: theme.spacing.unit * 0.875,
paddingRight: theme.spacing.unit,
paddingLeft: theme.spacing.unit,
},
dialog: {
width: 'calc(100% - 16px)',
},
inputRoot: {
width: '100%',
},
});
const AddButton = ({ onExecute }) => (
<div style={{ textAlign: 'center' }}>
<Button
color="primary"
onClick={onExecute}
title="Create new row"
>
New
</Button>
</div>
);
const EditButton = ({ onExecute }) => (
<IconButton onClick={onExecute} title="Edit row">
<EditIcon />
</IconButton>
);
const DeleteButton = ({ onExecute }) => (
<IconButton onClick={onExecute} title="Delete row">
<DeleteIcon />
</IconButton>
);
const CommitButton = ({ onExecute }) => (
<IconButton onClick={onExecute} title="Save changes">
<SaveIcon />
</IconButton>
);
const CancelButton = ({ onExecute }) => (
<IconButton color="secondary" onClick={onExecute} title="Cancel changes">
<CancelIcon />
</IconButton>
);
const commandComponents = {
add: AddButton,
edit: EditButton,
delete: DeleteButton,
commit: CommitButton,
cancel: CancelButton,
};
const Command = ({ id, onExecute }) => {
const CommandButton = commandComponents[id];
return (
<CommandButton
onExecute={onExecute}
/>
);
};
const availableValues = {
product: globalSalesValues.product,
region: globalSalesValues.region,
customer: globalSalesValues.customer,
};
const LookupEditCellBase = ({
availableColumnValues, value, onValueChange, classes,
}) => (
<TableCell
className={classes.lookupEditCell}
>
<Select
value={value}
onChange={event => onValueChange(event.target.value)}
input={(
<Input
classes={{ root: classes.inputRoot }}
/>
)}
>
{availableColumnValues.map(item => (
<MenuItem key={item} value={item}>
{item}
</MenuItem>
))}
</Select>
</TableCell>
);
export const LookupEditCell = withStyles(styles, { name: 'ControlledModeDemo' })(LookupEditCellBase);
const Cell = (props) => {
const { column } = props;
if (column.name === 'discount') {
return <ProgressBarCell {...props} />;
}
if (column.name === 'amount') {
return <HighlightedCell {...props} />;
}
return <Table.Cell {...props} />;
};
const EditCell = (props) => {
const { column } = props;
const availableColumnValues = availableValues[column.name];
if (availableColumnValues) {
return <LookupEditCell {...props} availableColumnValues={availableColumnValues} />;
}
return <TableEditRow.Cell {...props} />;
};
const getRowId = row => row.id;
class DemoBase extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
columns: [
{ name: 'product', title: 'Product' },
{ name: 'region', title: 'Region' },
{ name: 'amount', title: 'Sale Amount' },
{ name: 'discount', title: 'Discount' },
{ name: 'saleDate', title: 'Sale Date' },
{ name: 'customer', title: 'Customer' },
],
tableColumnExtensions: [
{ columnName: 'amount', align: 'right' },
],
rows: generateRows({
columnValues: { id: ({ index }) => index, ...globalSalesValues },
length: 12,
}),
sorting: [],
editingRowIds: [],
addedRows: [],
rowChanges: {},
currentPage: 0,
deletingRows: [],
pageSize: 0,
pageSizes: [5, 10, 0],
columnOrder: ['product', 'region', 'amount', 'discount', 'saleDate', 'customer'],
currencyColumns: ['amount'],
percentColumns: ['discount'],
};
const getStateDeletingRows = () => {
const { deletingRows } = this.state;
return deletingRows;
};
const getStateRows = () => {
const { rows } = this.state;
return rows;
};
this.changeSorting = sorting => this.setState({ sorting });
this.changeEditingRowIds = editingRowIds => this.setState({ editingRowIds });
this.changeAddedRows = addedRows => this.setState({
addedRows: addedRows.map(row => (Object.keys(row).length ? row : {
amount: 0,
discount: 0,
saleDate: new Date().toISOString().split('T')[0],
product: availableValues.product[0],
region: availableValues.region[0],
customer: availableValues.customer[0],
})),
});
this.changeRowChanges = rowChanges => this.setState({ rowChanges });
this.changeCurrentPage = currentPage => this.setState({ currentPage });
this.changePageSize = pageSize => this.setState({ pageSize });
this.commitChanges = ({ added, changed, deleted }) => {
let { rows } = this.state;
if (added) {
const startingAddedId = rows.length > 0 ? rows[rows.length - 1].id + 1 : 0;
rows = [
...rows,
...added.map((row, index) => ({
id: startingAddedId + index,
...row,
})),
];
}
if (changed) {
rows = rows.map(row => (changed[row.id] ? { ...row, ...changed[row.id] } : row));
}
this.setState({ rows, deletingRows: deleted || getStateDeletingRows() });
};
this.cancelDelete = () => this.setState({ deletingRows: [] });
this.deleteRows = () => {
const rows = getStateRows().slice();
getStateDeletingRows().forEach((rowId) => {
const index = rows.findIndex(row => row.id === rowId);
if (index > -1) {
rows.splice(index, 1);
}
});
this.setState({ rows, deletingRows: [] });
};
this.changeColumnOrder = (order) => {
this.setState({ columnOrder: order });
};
}
render() {
const {
classes,
} = this.props;
const {
rows,
columns,
tableColumnExtensions,
sorting,
editingRowIds,
addedRows,
rowChanges,
currentPage,
deletingRows,
pageSize,
pageSizes,
columnOrder,
currencyColumns,
percentColumns,
} = this.state;
return (
<Paper>
<Grid
rows={rows}
columns={columns}
getRowId={getRowId}
>
<SortingState
sorting={sorting}
onSortingChange={this.changeSorting}
/>
<PagingState
currentPage={currentPage}
onCurrentPageChange={this.changeCurrentPage}
pageSize={pageSize}
onPageSizeChange={this.changePageSize}
/>
<IntegratedSorting />
<IntegratedPaging />
<CurrencyTypeProvider for={currencyColumns} />
<PercentTypeProvider for={percentColumns} />
<EditingState
editingRowIds={editingRowIds}
onEditingRowIdsChange={this.changeEditingRowIds}
rowChanges={rowChanges}
onRowChangesChange={this.changeRowChanges}
addedRows={addedRows}
onAddedRowsChange={this.changeAddedRows}
onCommitChanges={this.commitChanges}
/>
<DragDropProvider />
<Table
columnExtensions={tableColumnExtensions}
cellComponent={Cell}
/>
<TableColumnReordering
order={columnOrder}
onOrderChange={this.changeColumnOrder}
/>
<TableHeaderRow showSortingControls />
<TableEditRow
cellComponent={EditCell}
/>
<TableEditColumn
width={120}
showAddCommand={!addedRows.length}
showEditCommand
showDeleteCommand
commandComponent={Command}
/>
<PagingPanel
pageSizes={pageSizes}
/>
</Grid>
<Dialog
open={!!deletingRows.length}
onClose={this.cancelDelete}
classes={{ paper: classes.dialog }}
>
<DialogTitle>
Delete Row
</DialogTitle>
<DialogContent>
<DialogContentText>
Are you sure to delete the following row?
</DialogContentText>
<Paper>
<Grid
rows={rows.filter(row => deletingRows.indexOf(row.id) > -1)}
columns={columns}
>
<CurrencyTypeProvider for={currencyColumns} />
<PercentTypeProvider for={percentColumns} />
<Table
columnExtensions={tableColumnExtensions}
cellComponent={Cell}
/>
<TableHeaderRow />
</Grid>
</Paper>
</DialogContent>
<DialogActions>
<Button onClick={this.cancelDelete} color="primary">
Cancel
</Button>
<Button onClick={this.deleteRows} color="secondary">
Delete
</Button>
</DialogActions>
</Dialog>
</Paper>
);
}
}
export default withStyles(styles, { name: 'ControlledModeDemo' })(DemoBase);
The font size of the text labelling the columns (e.g. product, region, amount) is fixed, and I see no parameters that can change it. Any ideas?
I think there are a few ways around this, the way I have used is having a fully controlled component.
Looks a little like this
<TableHeaderRow cellComponent={this.ExampleHeaderCell} />
Where ExampleHeaderCell is a component that would look something like this
ExampleHeaderCell = (props: any) => (<TableHeaderRow.Cell
className={exampleClass}
{...props}
key={column.name}
getMessage={() => column.title}
/>)
From there you can pass it a class as shown with exampleClass
You can take this further and have it customised for a particular column.
ExampleHeaderCells = (props: any) => {
const exampleClass = css({ backgroundColor: "blue" })
const { column } = props
if (column.name === "name") {
return (
<TableHeaderRow.Cell
className={exampleClass}
{...props}
key={column.name}
getMessage={() => column.title}
/>
)
}
return <TableHeaderRow.Cell {...props} key={column.name} getMessage={() => column.title} />
}
The example above is returning a specific cell with the exampleClass if the column name is equal to "name". Otherwise it just returns the regular TableHeaderRow.Cell