In my react application I'm using Material-UI enhanced table which is based on react-table and I would like to change the style of their rows.
Reading from documentation (https://material-ui.com/api/table-row/) in the component TableRow should be used the prop "classes" to change the style, but in the MaterialUi code props are read this way:
<TableRow {...row.getRowProps()}>
My question is how can I use the prop classes if the TableRow props are added automatically? I thought I needed to have this:
<TableRow classes="rowStyle ">
where rowStyle is:
const styles = {
rowStyle : {
padding: 10,
border: "1px solid red"
}
};
But obviously I can't this way, how can I add "classes" to the getRowProps() and the new style in it?
I couldn't find an explanation or a good example in official documentation or stackOverflow
Many thanks for the help
EnhancedTable.js:
import React from "react";
import Checkbox from "#material-ui/core/Checkbox";
import MaUTable from "#material-ui/core/Table";
import PropTypes from "prop-types";
import TableBody from "#material-ui/core/TableBody";
import TableCell from "#material-ui/core/TableCell";
import TableContainer from "#material-ui/core/TableContainer";
import TableFooter from "#material-ui/core/TableFooter";
import TableHead from "#material-ui/core/TableHead";
import TablePagination from "#material-ui/core/TablePagination";
import TablePaginationActions from "./TablePaginationActions";
import TableRow from "#material-ui/core/TableRow";
import TableSortLabel from "#material-ui/core/TableSortLabel";
import TableToolbar from "./TableToolbar";
import {
useGlobalFilter,
usePagination,
useRowSelect,
useSortBy,
useTable,
} from "react-table";
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef();
const resolvedRef = ref || defaultRef;
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate;
}, [resolvedRef, indeterminate]);
return (
<div>
<Checkbox ref={resolvedRef} {...rest} />
</div>
);
}
);
const inputStyle = {
padding: 0,
margin: 0,
border: 0,
background: "transparent",
};
// Create an editable cell renderer
const EditableCell = ({
value: initialValue,
row: { index },
column: { id },
updateMyData, // This is a custom function that we supplied to our table instance
}) => {
// We need to keep and update the state of the cell normally
const [value, setValue] = React.useState(initialValue);
const onChange = (e) => {
setValue(e.target.value);
};
// We'll only update the external data when the input is blurred
const onBlur = () => {
updateMyData(index, id, value);
};
// If the initialValue is changed externall, sync it up with our state
React.useEffect(() => {
setValue(initialValue);
}, [initialValue]);
return (
<input
style={inputStyle}
value={value}
onChange={onChange}
onBlur={onBlur}
/>
);
};
EditableCell.propTypes = {
cell: PropTypes.shape({
value: PropTypes.any.isRequired,
}),
row: PropTypes.shape({
index: PropTypes.number.isRequired,
}),
column: PropTypes.shape({
id: PropTypes.number.isRequired,
}),
updateMyData: PropTypes.func.isRequired,
};
// Set our editable cell renderer as the default Cell renderer
const defaultColumn = {
Cell: EditableCell,
};
const EnhancedTable = ({
columns,
data,
setData,
updateMyData,
skipPageReset,
}) => {
const {
getTableProps,
headerGroups,
prepareRow,
page,
gotoPage,
setPageSize,
preGlobalFilteredRows,
setGlobalFilter,
state: { pageIndex, pageSize, selectedRowIds, globalFilter },
} = useTable(
{
columns,
data,
defaultColumn,
autoResetPage: !skipPageReset,
// updateMyData isn't part of the API, but
// anything we put into these options will
// automatically be available on the instance.
// That way we can call this function from our
// cell renderer!
updateMyData,
},
useGlobalFilter,
useSortBy,
usePagination,
useRowSelect,
(hooks) => {
hooks.allColumns.push((columns) => [
// Let's make a column for selection
{
id: "selection",
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox. Pagination is a problem since this will select all
// rows even though not all rows are on the current page. The solution should
// be server side pagination. For one, the clients should not download all
// rows in most cases. The client should only download data for the current page.
// In that case, getToggleAllRowsSelectedProps works fine.
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
...columns,
]);
}
);
const handleChangePage = (event, newPage) => {
gotoPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setPageSize(Number(event.target.value));
};
const removeByIndexs = (array, indexs) =>
array.filter((_, i) => !indexs.includes(i));
const deleteUserHandler = (event) => {
const newData = removeByIndexs(
data,
Object.keys(selectedRowIds).map((x) => parseInt(x, 10))
);
setData(newData);
};
const addUserHandler = (user) => {
const newData = data.concat([user]);
setData(newData);
};
// Render the UI for your table
return (
<TableContainer>
<TableToolbar
numSelected={Object.keys(selectedRowIds).length}
deleteUserHandler={deleteUserHandler}
addUserHandler={addUserHandler}
preGlobalFilteredRows={preGlobalFilteredRows}
setGlobalFilter={setGlobalFilter}
globalFilter={globalFilter}
/>
<MaUTable {...getTableProps()}>
<TableHead>
{headerGroups.map((headerGroup) => (
<TableRow {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) => (
<TableCell
{...(column.id === "selection"
? column.getHeaderProps()
: column.getHeaderProps(column.getSortByToggleProps()))}
>
{column.render("Header")}
{column.id !== "selection" ? (
<TableSortLabel
active={column.isSorted}
// react-table has a unsorted state which is not treated here
direction={column.isSortedDesc ? "desc" : "asc"}
/>
) : null}
</TableCell>
))}
</TableRow>
))}
</TableHead>
<TableBody>
{page.map((row, i) => {
prepareRow(row);
return (
<TableRow {...row.getRowProps()}>
{row.cells.map((cell) => {
return (
<TableCell {...cell.getCellProps()}>
{cell.render("Cell")}
</TableCell>
);
})}
</TableRow>
);
})}
</TableBody>
<TableFooter>
<TableRow>
<TablePagination
rowsPerPageOptions={[
5,
10,
25,
{ label: "All", value: data.length },
]}
colSpan={3}
count={data.length}
rowsPerPage={pageSize}
page={pageIndex}
SelectProps={{
inputProps: { "aria-label": "rows per page" },
native: true,
}}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
ActionsComponent={TablePaginationActions}
/>
</TableRow>
</TableFooter>
</MaUTable>
</TableContainer>
);
};
EnhancedTable.propTypes = {
columns: PropTypes.array.isRequired,
data: PropTypes.array.isRequired,
updateMyData: PropTypes.func.isRequired,
setData: PropTypes.func.isRequired,
skipPageReset: PropTypes.bool.isRequired,
};
export default EnhancedTable;
Correct me if i'm wrong, but i think the first step to your solution is the correct definition of styles for the material-ui element. I can't say for certain if there is another way to generate these styles, but a simple object such as:
const inputStyle = { padding: 0, margin: 0, border: 0, background: "transparent", };
will probably not work. You probably have to use the material styles for that.
import { makeStyles } from "#material-ui/core/styles";
const useStyles = makeStyles({
root: {
border: "1px solid red",
padding: 10
},
});
and then you have to use the style hook in the component definition:
const classes = useStyles();
When overriding a material-ui definition this part is the important one to define which part is going to overriden (not allowed to include pictures yet, sorry):
Material-Ui CSS keys for Table Row
Then you can override the style <TableRow classes={{ root: classes.root }}> or in your case maybe more like <TableRow classes={{ root: classes.root }} {...row.getRowProps()}>
An additional problem you might face is that you have to override the style of the TableCells too, because the overlap the TableRow border.
I have here a code sandbox that is by no means perfect, but should help you on the right track: https://codesandbox.io/s/material-demo-535zq?file=/demo.js
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles(() => ({
rowStyle : {
padding: 10,
border: "1px solid red"
}
}));
const EnhancedTable = ()=>{
const classes = useStyles();
return(
<TableRow className={classes.rowStyle}/>
)
}
Related
I have two buttons that show two different components when toggling them. For UX reasons (to know which component is showing) I would like to style the buttons according to if the value of the state is true or false (give them an underline and a darker color if the state is true). Is this possible in any way?
This is my GitHub repo: https://github.com/uohman/Portfolio2022
And this is the component where I handle the buttons:
`
import React, { useState } from 'react'
import ReactDOM from 'react-dom';
import { Subheading } from 'GlobalStyles';
import { FrontendProjects } from './FrontendProjects'
import { GraphicDesignProjects } from './GraphicDesignProjects';
import 'index.css'
export const FeaturedProjects = () => {
const [buttons, setButtons] = useState([
{ label: 'Development', value: true },
{ label: 'Graphic design', value: false }
]);
const handleButtonsChange = () => (label) => {
const newButtonsState = buttons.map((button) => {
if (button.label === label) {
return (button = { label: button.label, value: true });
}
return {
label: button.label,
value: false
};
});
setButtons(newButtonsState);
};
return (
<>
<Subheading><span>Featured projects</span></Subheading>
<SpecialButton {...{ buttons, setButtons, handleButtonsChange }} />
{buttons[0].value && <FrontendProjects />}
{buttons[1].value && <GraphicDesignProjects />}
</>
);
};
const SpecialButton = ({ buttons, setButtons, handleButtonsChange }) => {
return (
<div className="button-container">
{buttons.map((button, index) => (
<button
key={`${button.label}-${index}`}
onClick={() => handleButtonsChange({ buttons, setButtons })(button.label)}>
{button.label.toUpperCase()}
</button>
))}
</div>
);
};
const rootElement = document.getElementById('root');
ReactDOM.render(<FeaturedProjects />, rootElement);
`
I've given the buttons the pseudo element :focus and that nearly solves my problem, but still as a default the buttons are the same color although it is one of the components that is showing. Thankful for suggestions on how to solve this!
You can provide a style props to any html component.
You should pass an object where attributes are camelcased.
<button
style={{ // double bracket to pass an object
backgroundColor: yourVariable ? 'red' : undefined // notice css background-color became backgroundColor
}}
>
{button.label.toUpperCase()}
</button>
You can do the same with classes
<button
className={yourVariable && "yourClass"}
>
{button.label.toUpperCase()}
</button>
You can set styles for button based on a condition.
In this use case, you already have the state button.value which can be used as a condition to set inline styles (or classes) for the mapped button.
Example:
const SpecialButton = ({ buttons, setButtons, handleButtonsChange }) => {
return (
<div className="button-container">
{buttons.map((button, index) => (
<button
key={`${button.label}-${index}`}
// ๐ This property is added
style={{
backgroundColor: button.value ? "#aaa" : "#eee",
textDecoration: button.value ? "underline" : "none",
}}
onClick={() =>
handleButtonsChange({ buttons, setButtons })(button.label)
}
>
{button.label.toUpperCase()}
</button>
))}
</div>
);
};
The buttons are set to become darker when selected in the above example, but you can further customize the styles for the desired result.
More about inline styles
On a side note, it is not necessary to pass state values to the the event by onClick={() => handleButtonsChange({ buttons, setButtons })(button.label)}.
The parent component always have these values, so you do not need to pass it down to SpecialButton and pass it back.
Hope this will help!
Full example:
import React, { useState } from "react";
import ReactDOM from "react-dom";
import { Subheading } from "GlobalStyles";
import { FrontendProjects } from "./FrontendProjects";
import { GraphicDesignProjects } from "./GraphicDesignProjects";
import "index.css";
export const FeaturedProjects = () => {
const [buttons, setButtons] = useState([
{ label: "Development", value: true },
{ label: "Graphic design", value: false },
]);
const handleButtonsChange = (label) => {
const newButtonsState = buttons.map((button) => {
if (button.label === label) {
return (button = { label: button.label, value: true });
}
return {
label: button.label,
value: false,
};
});
setButtons(newButtonsState);
};
return (
<>
<Subheading>
<span>Featured projects</span>
</Subheading>
<SpecialButton {...{ buttons, handleButtonsChange }} />
{buttons[0].value && <FrontendProjects />}
{buttons[1].value && <GraphicDesignProjects />}
</>
);
};
const SpecialButton = ({ buttons, handleButtonsChange }) => {
return (
<div className="button-container">
{buttons.map((button, index) => (
<button
key={`${button.label}-${index}`}
// ๐ This property is added
style={{
backgroundColor: button.value ? "#aaa" : "#eee",
textDecoration: button.value ? "underline" : "none",
}}
onClick={() =>
handleButtonsChange(button.label)
}
>
{button.label.toUpperCase()}
</button>
))}
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<FeaturedProjects />, rootElement);
I wanted to change the style of an item with one click in a list and remove it if I click another item
I did like this but when I click on the second it doesnโt change to the first
const ref = useRef();
const handleClick = () => {
if (ref.current.style.backgroundColor) {
ref.current.style.backgroundColor = '';
ref.current.style.color = '';
} else {
ref.current.style.backgroundColor = 'green';
ref.current.style.color = 'white';
}
};
<Card ref={ref} elevation={6} style={{ marginBottom: "5px"}} onClick={()=>{ handleClick()}} >
<CardContent style={{ height: "10px" }}>
<Typography >
{user}
</Typography>
</CardContent>
</Card>
);
};
any help please!
I like using a package like classnames ( yarn add classnames or npm i classnames) to apply conditional styling through classes rather than having to inline the element's styling directly.
You could pass the selected attribute to your Card component using React's useState (or Redux) and then apply conditional styling to selected cards (i.e. <Card selected />).
Component.js
import { useState } from 'react';
import { useSelector } from 'react-redux';
import Card from './Card';
const Component = () => {
const [selectedId, setSelectedId] = useState(null);
const items = useSelector(state => state.items);
const handleClick = (id) => {
setSelectedId(id);
};
return items.map(({id}) =>
<Card
key={id}
onClick={() => handleClick(id)}
selected={id === selectedId}
>
...
</Card>
);
};
export default Component;
Card.js
import { classNames } from 'classnames';
const Card = ({ children, onClick, selected = false }) => (
<div
className={
classNames('Card', {
'Card--Selected': selected
})
}
onClick={onClick}
>
{ children }
</div>
);
export default Card;
Card.scss
.Card {
// Card styling...
&--Selected {
// Selected card styling...
}
}
I am trying to build a simple navbar but when I define a setResponsivness function inside my useEffect
I am getting the error Rendered fewer hooks than expected. This may be caused by an accidental early return statement. I looked at similar answers for the same but till wasn't able to fix
Here s my code
import React,{useEffect,useState} from 'react'
import {AppBar ,Toolbar, Container ,makeStyles,Button, IconButton} from '#material-ui/core'
import MenuIcon from '#material-ui/icons/Menu'
const usestyles = makeStyles({
root:{
display:'flex',
justifyContent:'space-between' ,
maxWidth:'700px'
},
menubtn:{
fontFamily: "Work Sans, sans-serif",
fontWeight: 500,
paddingRight:'79px',
color: "white",
textAlign: "left",
},
menuicon:{
edge: "start",color: "inherit",paddingLeft:'0'
}
})
const menudata = [
{
label: "home",
href: "/",
},
{
label: "About",
href: "/about",
},
{
label: "Skill",
href: "/skills",
},
{
label: "Projects",
href: "/projects",
},
{
label: "Contact",
href: "/contact",
},
];
//yet to target link for the smooth scroll
function getmenubuttons(){
const {menubtn} = usestyles();
return menudata.map(({label,href})=>{
return <Button className={menubtn}>{label}</Button>
})
}
//to display navbar on desktop screen
function displaydesktop(){
const { root } = usestyles() //destructuring our custom defined css classes
return <Toolbar ><Container maxWidth={false} className={root}>{getmenubuttons()}</Container> </Toolbar>
}
//to display navbar on mobile screen
function displaymobile(){
const {menuicon} =usestyles() ;
return <Toolbar><IconButton className={menuicon}><MenuIcon /> </IconButton></Toolbar>
}
function Navbar() {
const [state, setState] = useState({mobileview:false});
const {mobileview} = state;
useEffect(() => {
const setResponsiveness = () => {
return window.innerWidth < 900
? setState((prevState) => ({ ...prevState, mobileview: true }))
: setState((prevState) => ({ ...prevState, mobileview: false }));
};
setResponsiveness();
window.addEventListener("resize", () => setResponsiveness());
}, []);
return (
<div>
<AppBar> {mobileview?displaymobile():displaydesktop()} </AppBar>
</div>
)
}
export default Navbar;
Your problem seems to be here
{mobileview?displaymobile():displaydesktop()}
For example the displaymobile function inside uses hooks right (usestyles)? Then it means you are rendering hooks inside conditions (mobileview being condition) which is not allowed by rules of hooks.
You can fix it like this:
<div>
<AppBar> {mobileview ? <Displaymobile /> : <Displaydesktop />} </AppBar>
</div>
Also change definition of component using capital letters as that is how react refers to components. e.g.
function Displaydesktop() {
const { root } = usestyles(); //destructuring our custom defined css classes
return (
<Toolbar>
<Container maxWidth={false} className={root}>
{getmenubuttons()}
</Container>{" "}
</Toolbar>
);
}
Now we consume them as components. Probably when you used lower case letters and called those as functions in your render, react interpreted them as custom hooks, hence the warnings.
How to create a Datagrid without a List in React-Admin?
In React-admin to be able to use Datagrid to show the values you need to nest it inside a List like that:
<List {...props}>
<Datagrid>
<Textfield source"name" />
<Datagrid />
<List/>
But I need to use the dDatagrid outside of the List. The values of the Datagrid must to be shown in a screen of the type inside a Tab.
Here how I solved that problem using React-Admin 2.9
First I used The import { Query } from 'react-admin'; to fetch the data from the endpoint data/product and after that It converted the IDs to the key of it's own data.
To the commponent CustomDatagrid was passed two arrays the will be used to show the values. The first is a array of IDs and the second array is the array that contains the data and uses IDs as its key to be able to access the values.
ProductShow.js
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
TextField,
Query,
showNotification,
// ReferenceField,
DateField,
} from 'react-admin';
import CustomDatagrid from './CustomDatagrid';
const convertKeyToIndice = (datas) => {
const { data } = datas;
let ids = [];
const dataKey = [];
if (data) {
ids = data.map((elemento) => {
dataKey[elemento.id] = elemento;
return elemento.id;
});
return ({ ids, dataKey });
}
return ({});
};
const ProductShow = (props) => {
const { record } = props;
const { productId, dateValue } = record;
const [newPage, setNewPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(50);
const filter = {
pagination: { page: newPage + 1, perPage: rowsPerPage },
sort: { field: 'id', order: 'ASC' },
filter: { productId, dateValue: dateValue },
};
return (
<Query type="GET_LIST" resource="data/product" payload={filter}>
{(datas) => {
if (datas.loading && !datas.error) { return <div>Wait...</div>; }
if (datas.error) {
props.showNotification('Not Found');
return <div />;
}
const dataGridValues = {
...convertKeyToIndice(datas),
total: datas.total,
rowsPerPage,
setRowsPerPage,
newPage,
setNewPage,
};
return (
<>
<CustomDatagrid dataGridValues={dataGridValues}>
{/* <ReferenceField
sortBy="product.id"
source="productId"
reference="product"
linkType={false}
allowEmpty
{...props}
label="product"
>
<TextField source="name" />
</ReferenceField> */}
<DateField label="Date" source="valueDate" showTime />
<TextField label="Value1" source="value1" />
<TextField label="Value2" source="value2" />
<TextField label="Value3" source="value3" />
<TextField label="Value4" source="value4" />
<TextField label="Value5" source="value5" />
</CustomDatagrid>
</>
);
}}
</Query>
);
};
ProductShow.propTypes = {
productId: PropTypes.string.isRequired,
dateValue: PropTypes.string.isRequired,
showNotification: PropTypes.func.isRequired,
record: PropTypes.oneOfType([PropTypes.object]).isRequired,
};
export default connect(null, { showNotification })(ProductShow);
In the TableHead it shows the label of each column following the order that you wrap the Components in the CustomDatagrid inside the parent ProductShow component.
To Show The Components Like the List of React-Admin would show, is used the
{React.cloneElement(child,
{ record: dataKey[id] },
(child.props.children ? child.props.children : null))}
CustomDatagrid.js
import React from 'react';
import {
Table,
TableRow,
TableHead,
TableCell,
TableBody,
TablePagination,
} from '#material-ui/core';
import PropTypes from 'prop-types';
const CustomDatagrid = (propsDataGrid) => {
const { children, dataGridValues } = propsDataGrid;
const {
dataKey,
ids,
total,
rowsPerPage,
setRowsPerPage,
setNewPage,
newPage,
} = dataGridValues;
const handleChangePage = (event, page) => {
setNewPage(page);
};
const handleChangeRowsPerPage = (event) => {
const vlrDecimal = parseInt(event.target.value, 10);
setRowsPerPage(vlrDecimal);
setNewPage(0);
};
return (
<>
<Table style={{ width: '100%' }}>
<TableHead>
<TableRow>
{children && children.map(({ props }) => (
<TableCell>
{props && props.label ? props.label : props.source}
</TableCell>
))
}
</TableRow>
</TableHead>
<TableBody>
{ids && ids.map(id => (
<TableRow>
{React.Children.map(children,
child => (
<TableCell>
{React.cloneElement(child,
{ record: dataKey[id] },
(child.props.children ? child.props.children : null))}
</TableCell>
))}
</TableRow>
))
}
</TableBody>
</Table>
<TablePagination
rowsPerPageOptions={[50, 100, 250]}
component="div"
count={total}
rowsPerPage={rowsPerPage}
page={newPage}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
labelRowsPerPage="Results per Page:"
/>
</>
);
};
CustomDatagrid.propTypes = {
source: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
};
export default CustomDatagrid;
I added redux to create-react-app and i've been trying to get a navigator to work. I do this by having the active "page link" highlighted. The code I use for this is a combination of react hooks (using state to remember current page) and the npm package classNames.
classNames(object['key'] && classes.activeItem)
So here I have object['key'] evaluate to true when that particular item is activated so that the item gains the activeItem class.
When I replace object['key'] with true, it works. When I console.log object['key'] after I click it, it also evaluates to true.
Why isn't this working? Thanks!
import React, { useEffect, memo } from 'react';
import { bindActionCreators, compose } from 'redux';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '#material-ui/core/styles';
import { loadPage } from './actions';
import { uploadFile } from '../uploadFile/actions';
import _ from 'lodash';
const styles = theme => ({
item: {
paddingTop: 4,
paddingBottom: 4,
color: 'rgba(255, 255, 255, 0.7)',
'&:hover': {
backgroundColor: 'rgba(255, 255, 255, 0.08)',
},
},
itemPrimary: {
color: 'inherit',
fontSize: theme.typography.fontSize,
'&$textDense': {
fontSize: theme.typography.fontSize,
},
},
itemActiveItem: {
color: '#4fc3f7',
},
textDense: {}
});
function Navigator(props) {
const { classes, curPage, onUploadFile, onPageChange, dispatch, ...other } = props;
let activePage = {
'invite': false,
}
useEffect(() => {
if(!curPage){
onPageChange('search');
}
activePage = _.mapValues(activePage, () => false);
activePage[curPage] = true
});
return (
<Drawer variant="permanent" {...other}>
<List disablePadding>
<ListItem button className={classNames(classes.logo)}>
<img src={require("assets/img/logo.png")} alt={''}/>
</ListItem>
<ListItem className={classes.categoryHeader} >
<ListItemText classes={{ primary: classes.categoryHeaderPrimary }}>
Files
</ListItemText>
</ListItem>
<ListItem
button
dense
className={classNames(classes.item, activePage['invite'] && classes.itemActiveItem)}
onClick={() => {onPageChange('invite')}}
>
<ListItemIcon><PeopleIcon /></ListItemIcon>
<ListItemText classes={{ primary: classes.itemPrimary, textDense: classes.textDense }}>
Invite To Your Team
</ListItemText>
</ListItem>
</List>
</Drawer>
);
}
Navigator.propTypes = {
classes: PropTypes.object.isRequired,
onPageChange: PropTypes.func.isRequired,
onUploadFile: PropTypes.func.isRequired
};
const mapStateToProps = (state) => {
const { curPage } = state.app;
return { curPage };
};
const mapDispatchToProps = (dispatch) => {
return {
onPageChange: bindActionCreators(loadPage, dispatch),
onUploadFile: bindActionCreators(uploadFile, dispatch),
dispatch
};
};
const withConnect = connect(
mapStateToProps,
mapDispatchToProps
);
export default compose(withConnect, memo, withStyles(styles))(Navigator);
Note that function passed to the useEffect hook is always run after the render.
Your useEffect doesn't cause a re-render for component to see the changes. Only change to state causes a re-render. If you want a re-render, you need to use useState hook first, and then you need to setState from within the useEffect hook. Or, you could just run these two lines as part of a render (removing them from the useEffect hook, putting them outside):
activePage = _.mapValues(activePage, () => false);
activePage[curPage] = true
useEffect(() => {
if(!curPage){
onPageChange('search');
}
});
But as I'm looking at your code, I think you could just use curPage === 'invite' && classes.itemActiveItem instead of activePage['invite'] && classes.itemActiveItem and remove those unnecessary lines related to activePage object. It would make things much easier.