React align right/hide items on ANTD 4.21 Menu - css

Is there a way I can add different classes or an attribute to align right 2 items of this ant design top navigation menu? Also how can I hide an item conditionally? IE if there's an user logged in, I want to hide an item.
import { HomeOutlined, SettingOutlined, LoginOutlined, UserAddOutlined} from '#ant-design/icons';
import { Menu } from 'antd';
import { useState } from 'react';
const items = [
{
label: 'Home',
key: 'home',
icon: <HomeOutlined />,
},
{
label: 'Username',
key: 'SubMenu',
icon: <SettingOutlined />,
children: [
{
type: 'group',
children: [
{
label: 'Option 1',
key: 'setting:1',
},
{
label: 'Option 2',
key: 'setting:2',
},
],
},
],
},
{
label: 'Login',
key: 'login',
icon: <LoginOutlined />
},
{
label: 'Register',
key: 'register',
icon: <UserAddOutlined />,
},
];
const Header = () => {
const [current, setCurrent] = useState('home');
const onClick = (e) => {
setCurrent(e.key);
};
return (
<Menu onClick={onClick} selectedKeys={[current]} mode="horizontal" items={items} />
);
};
export default Header;
I'm using ant design's top navigation menu: https://ant.design/components/menu/#API
I checked their documentation and other places but I can't seem to figure it out. I would appreciate any help.
Thanks

I don't know if it is too late to respond :)
As far as I know, there is no "one-line" solution for this. You should make the conditions with JS using conditional JSX.
For example (in JSX, in the return expression in your React Component):
{checkedCondition &&
<Menu type one .../>
}
{uncheckedCondition &&
<Menu type two .../>
}

Related

Adding controls for nested proptypes in storybook

I am trying to add a multi-select control using argTypes in storybook for a button component which takes propTypes in below format :
type ButtonProps = {
params: { FirstParam: string; SecondParam: string };
fields: Fields;
};
And the below is the code where I am trying to specify the control type for firstParam :
export default {
title: 'components/Button',
component: Default,
argTypes: {
params: {
FirstParam: {
name: 'FirstParam',
description: 'grid styling',
control: { type: 'multi-select', disable: false },
options: ['b', 'c', 'd'],
defaultValue: 'b c d',
},
SecondParam: {
name: 'SecondParam',
description: 'button styling',
control: 'multi-select',
options: ['none', 'secondary-button'],
},
},
},
decorators: [(story) => <div className="grid grid-cols-12">{story()}</div>],
} as ComponentMeta<typeof Default>;
const Template: ComponentStory<typeof Default> = (args) => <Default {...args} />;
export const Primary = Template.bind({});
Primary.args = {
fields: {
Link: {
value: {
href: 'https://www.google.com/',
target: '_blank',
text: 'Find Installer',
},
},
},
};
But it doesn't bind the control and breaks the storybook component.
Is it possible to have controls like multi-select working for the above kind of buttonProps?

how can I make the data no longer pass in the adjacent column when there is no space in react table bootstrap?

I would like when there is no space to lower the letters that do not fit with a lower level.Can i resolve this using css ?
I tried in various ways I read the documentation but nothing worked just changing the color :(
I really need to know if there is a solution as soon as possible, thanks in advance :)
There is my table when there is no space
There is my code
import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css";
import "bootstrap/dist/css/bootstrap.min.css";
import BootstrapTable from "react-bootstrap-table-next";
import paginationFactory from "react-bootstrap-table2-paginator";
import Sidebar from "./sidebar/Sidebar";
import 'bootstrap/dist/css/bootstrap.css';
import React, { useEffect, useState } from "react";
import axiosInstance from "./axios";
import cellEditFactory from 'react-bootstrap-table2-editor';
import { Button } from "react-bootstrap";*
const UsersList = () => {
const [users,setUsers] = useState([]);
useEffect( () => {
axiosInstance.get("users")
.then(res => {
const val = res.data;
setUsers( val);
})
.catch(error => {
console.log(error);
});
}, []);
let isFollow = true;
const onFollowChanged =() => {
isFollow = !isFollow;
console.log(isFollow);
}
const linkFollow = (cell, row, rowIndex, formatExtraData) => {
return (
<Button
onClick={() => {
onFollowChanged();
}}
>
Follow
</Button>
);
};
onFollowChanged.bind();
const columns = [
{
dataField: 'index',
text: 'ID',
formatter: (cell, row, rowIndex, formatExtraData) => {
return rowIndex + 1;
},
sort: true,
},
{
dataField: "username",
text: "Username",
},
{
dataField: "email",
text: "Email",
},
{
dataField: "fullName",
text: "Full Name"
},
{
dataField: "address",
text: "Address"
},
{
dataField: "status",
text: "Status"
},
{
dataField: "follow",
text: "EDIT",
editable: false,
formatter: linkFollow
}
];
const rowEvents = {
onClick: (e, row, rowIndex) => {
window.location.assign("/home");
}
};
return (
<div>
<Sidebar />
<div className="container" style={{ padding: "20px" }}>
<BootstrapTable
striped hover condensed
trClassName='tr-string-example'
keyField="id"
data={users}
columns={columns}
pagination={paginationFactory({ sizePerPage: 5 })}
cellEdit={ cellEditFactory({ mode: 'click' }) }
/>
</div>
</div>
);
}
export default UsersList;

Rendered fewer hooks than expected error in the return statement

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 style (add css) to material-table (React)?

I've been searching for a few days now and can't find anything. I'm using material-table in React but can't figure how to add css in headers (columns of the table) and the content [like changing font size, width and making table rows of striped background].
Can anyone tell me how I can do it?
For reference, here's the current Material table I have and I want to make the rows striped and change the look of headers (column names)
<MaterialTable
title="Title"
columns={this.state.columns}
data={newDataTable}
options={{
selection: true
}}
options={{
search: false,
sorting: true
}}
actions={[
{
icon: () => <Checkbox />,
tooltip: 'checkbox'
},
{
icon: () => <InfoIcon />,
tooltip: 'info',
onClick: (event, item) => {
this.setState({
isOpen: true,
selectedItem: item
});
}
}
]}
/>
</div>
Edit: Also, can't figure out how to change the content of the rows. Like for example I want to add an icon in front of every item corresponding to its data. Currently, I'm just using a js array to display the static data but I can't edit it.
Just define the styles within the columns property:
this.setState({
columns: {[
{
title: 'Name', field: 'name',
cellStyle: {
backgroundColor: '#039be5',
color: '#FFF'
},
headerStyle: {
backgroundColor: '#039be5',
}
},
// Other columns
]}
});
See https://material-table.com/#/docs/features/styling
if you want to add an icon inside your data( rows/cells), you can use built-in render callback in columns definition like this :
const handleTableColumns = (cols) => {
return cols.map((col) => ({
...col,
render: (rowData) => {
return (
<span style = {{display: 'flex'}} >
<KeyboardArrowRightIcon />
{ rowData[col.id]}
</span>
);
};
}))
};
this will insert the icon <KeyboardArrowRightIcon /> in front of every cell of each row, so in materialTable component you have to use handleTableColumns as columns :
<MaterialTable
style={{ padding: '0 8px' }}
columns={this.handleTableColumns(this.state.columns)}
data={data}
...
...
/>
Options can be passed with a key rowstyle. Where you can configure the background colour.
< MaterialTable title = "Title"
columns = {
this.state.columns
}
data = {
newDataTable
}
options = {
{
selection: true,
rowStyle: (row) => {
const rowStyling = {
fontSize: "14px",
fontFamily: "latoregular"
};
if (row.sl % 2) {
rowStyling.backgroundColor = "#f2f2f2";
}
return rowStyling;
},
}
}
options = {
{
search: false,
sorting: true,
}
}
actions = {
[{
icon: () =>
<
Checkbox / > ,
tooltip: "checkbox",
}, {
icon: () =>
<
InfoIcon / > ,
tooltip: "info",
onClick: (event, item) => {
this.setState({
isOpen: true,
selectedItem: item,
});
},
}, ]
}
/>;

Semantic-ui-react input Fields are clearing if i switch from one tab to other

need to hold input values after changing tab.let me consider each tab pane contains form inputs ,the form fields are clearing if i switch between tabs, how to hold these values.
import React from 'react'
import { Tab ,Input} from 'semantic-ui-react'
const panes = [
{ menuItem: 'Tab 1', render: () => <Tab.Pane attached={false}><Input /></Tab.Pane> },
{ menuItem: 'Tab 2', render: () => <Tab.Pane attached={false}></Tab.Pane> },
{ menuItem: 'Tab 3', render: () => <Tab.Pane attached={false}></Tab.Pane> },
]
const TabExampleSecondaryPointing = () => (
<Tab menu={{ secondary: true, pointing: true }} panes={panes} />
)
export default TabExampleSecondaryPointing
is there any way to hold input values after tab change.
Yess got it working!!, here is the code
import React from 'react'
import { List, Label, Tab ,Input} from 'semantic-ui-react'
const panes = [
{ menuItem: 'Tab 1', pane: { key: 'tab1', content: <Input />, size: 'massive' } },
{ menuItem: 'Tab 2', pane: { key: 'tab2', content: 'This tab has a center aligned text', textAlign: 'center' } },
{ menuItem: 'Tab 3', pane: { key: 'tab3', content: <div>This tab contains an <Label>JSX</Label> element</div> } },
{ menuItem: 'Tab 4',
pane: (
<Tab.Pane key='tab4'>
<p>This tab has a complex content</p>
<List>
<List.Item>Apples</List.Item>
<List.Item>Pears</List.Item>
<List.Item>Oranges</List.Item>
</List>
</Tab.Pane>
) },
]
const TabExampleContentShorthand = () => (
<Tab panes={panes} renderActiveOnly={false} />
)
export default TabExampleContentShorthand
renderActiveOnly={false} only works when you provide the pane content in a pane object therefore if render is used for the pane content, renderActiveOnly={false} will not work.
Examples (from the question):
renderActiveOnly={false} will not work:
const panes = [
{ menuItem: 'Tab 1', render: () => <Tab.Pane attached={false}><Input /></Tab.Pane> },
]
renderActiveOnly={false} will work:
const panes = [
{ menuItem: 'Tab 1', pane: { key: 'tab1', content: <Input />, size: 'massive' } },
]
It's a known issue with API of the Tab component, by default it renders only current active tab. So when you switch to another tab, it looses state.
Take a look on the example with renderActiveOnly={false}, it should solve your problem.

Resources