Why the theme doesnt change to darkmode - using Material ui ThemeProvider? What am I doing wrong? - material-ui

on my app.tsx file
<ThemeProvider theme={darkTheme}>
<CssBaseline />
<Paper>
<Layout>
<Component {...pageProps} />
</Layout>
{/* <AnimatedWrapper children></AnimatedWrapper> */}
</Paper>
</ThemeProvider>
then I made a useDarkMode.ts function
export const useDarkMode = () => {
const [darkState, setDarkState] = useState<boolean>(false);
const palletType = darkState ? 'dark' : 'light';
const darkTheme = createMuiTheme({
palette: {
type: palletType,
},
});
return { darkState, setDarkState, darkTheme };
};
and I am using Switcher from material ui on the NavBar component
export const NavBar = (): JSX.Element => {
const { darkState, setDarkState } = useDarkMode();
const classes = useStyles();
...
<Typography className={classes.logoText}>
<Switch checked={darkState} onChange={() => setDarkState(!darkState)} />
</Typography>

Related

How can I add linear-gradient to my Material-UI (v5.11.5) background

I have an Appbar that has a fixed colour background that has been applied using the createTheme module for material-ui. I have been asked to apply a linear gradient for a transitioning color effect to the Appbar. I have tried using palette: {
background: {
paper: '-webkit-linear-gradient(to left, #30e8bf, #ff8235)',
}, in my createTheme then using sx={{ bgcolor: 'background.paper' }} in my Appbar.
Any suggestion to changes I need to make ?
import * as React from 'react'
import AppBar from '#mui/material/AppBar'
import Box from '#mui/material/Box'
import Toolbar from '#mui/material/Toolbar'
import Stack from '#mui/material/Stack'
import Button from '#mui/material/Button'
import Tabs from '#mui/material/Tabs'
import Tab from '#mui/material/Tab'
import Typography from '#mui/material/Typography'
import IconButton from '#mui/material/IconButton'
import MenuIcon from '#mui/icons-material/Menu'
import AccountCircle from '#mui/icons-material/AccountCircle'
import Switch from '#mui/material/Switch'
import FormControlLabel from '#mui/material/FormControlLabel'
import FormGroup from '#mui/material/FormGroup'
import MenuItem from '#mui/material/MenuItem'
import Menu from '#mui/material/Menu'
import CssBaseline from '#mui/material/CssBaseline'
import { ThemeProvider, createTheme } from '#mui/material/styles'
import Chip from '#mui/material/Chip'
import Check from '#mui/icons-material/Check'
const finalTheme = createTheme({
components: {
// Name of the component
MuiButton: {
styleOverrides: {
// Name of the slot
root: {
// Some CSS
fontSize: '3rem',
backgroundColor: '#fff',
},
},
},
},
typography: {
// In Chinese and Japanese the characters are usually larger,
// so a smaller fontsize may be appropriate.
fontSize: 15,
},
palette: {
background: {
paper: '-webkit-linear-gradient(to left, #30e8bf, #ff8235)',
},
},
})
export default function NavBar() {
const [auth, setAuth] = React.useState(true)
const [anchorEl, setAnchorEl] = React.useState(null)
const [value, setValue] = React.useState('apple')
const handleChange = (event) => {
setAuth(event.target.checked)
}
const handleMenu = (event) => {
setAnchorEl(event.currentTarget)
}
const handleClose = () => {
setAnchorEl(null)
}
return (
<React.StrictMode>
<Box sx={{ flexGrow: 1 }}>
<ThemeProvider theme={finalTheme}>
<AppBar position="static" sx={{ bgcolor: 'background.paper' }}>
<Toolbar>
<IconButton
size="large"
edge="start"
color="inherit"
aria-label="menu"
sx={{ mr: 2 }}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" component="div" sx={{ flexGrow: 1 }} />
<Tab value="0" label="Sessions" />
<Tab value="1" label="Gallery" />
<Tab value="2" label="About Us" />
{auth && (
<div>
<IconButton
size="large"
aria-label="account of current user"
aria-controls="menu-appbar"
aria-haspopup="true"
onClick={handleMenu}
color="inherit"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
</Menu>
</div>
)}
</Toolbar>
</AppBar>
</ThemeProvider>
</Box>
</React.StrictMode>
)
}

Tab Color disorder and single click ripple effect disappears after I add active tabs

Here's my header copmponent where I try to apply active tabs effect, the text completely disappers.
Header.js
import {
AppBar,
Toolbar,
useScrollTrigger,
Typography,
Tabs,
Tab,
Button,
} from "#mui/material";
import DeveloperModeIcon from "#mui/icons-material/DeveloperMode";
import { Box } from "#mui/system";
import { styled } from "#mui/material/styles";
import { Link } from "react-router-dom";
const Header = () => {
const [value, setValue] = useState(window.location.pathname);
function ElevationScroll(props) {
const { children } = props;
const trigger = useScrollTrigger({
disableHysteresis: true,
threshold: 0,
});
return React.cloneElement(children, {
elevation: trigger ? 4 : 0,
});
}
const TabComponent = styled(Tab)(({ theme }) => ({
fontWeight: 600,
fontSize: "1rem",
textTransform: "none",
// color: theme.palette.common.white,
}));
const onTabChangeHandler = (event, newValue) => {
setValue(newValue);
};
return (
<React.Fragment>
<ElevationScroll>
<AppBar position="fixed">
<Toolbar>
<DeveloperModeIcon sx={{ fontSize: "3rem" }} />
<Typography variant="h4">Lopxhan Development</Typography>
<Tabs
sx={{ marginLeft: "auto" }}
value={value}
onChange={onTabChangeHandler}
aria-label="secondary tabs example"
>
<TabComponent label="Home" component={Link} to="/" value="/" />
<TabComponent
label="Services"
component={Link}
to="/services"
value="/services"
disableRipple
/>
<TabComponent
label="Projects"
component={Link}
to="/projects"
value="/projects"
/>
<TabComponent
label="About Us"
component={Link}
to="/aboutus"
value="/aboutus"
/>
<TabComponent
label="Conatct Us"
component={Link}
to="/contactus"
value="/contactus"
/>
</Tabs>
<Button
variant="contained"
color="secondary"
sx={{
borderRadius: "50px",
fontWeight: 600,
}}
>
Get a Quote
</Button>
</Toolbar>
</AppBar>
</ElevationScroll>
<Box
sx={[
(theme) => ({
marginBottom: {
...theme.mixins.toolbar,
},
}),
]}
/>
</React.Fragment>
);
};
export default Header;
Theme.js
const arcBlue = "#0B72B9";
const arcOrange = "#e67700";
const arcGrey = "#868686";
export const appTheme = createTheme({
palette: {
common: {
blue: arcBlue,
orange: arcOrange,
white: "#fff",
},
primary: {
main: arcBlue,
},
secondary: {
main: arcOrange,
},
},
});
App.js
import { Routes, Route } from "react-router-dom";
import { ThemeProvider } from "#mui/material/styles";
import Header from "./components/UI/Header";
import { appTheme } from "./components/UI/Theme";
import HomePage from "./components/pages/HomePage";
import ServicesPage from "./components/pages/ServicesPage";
import ProjectsPage from "./components/pages/ProjectsPage";
import GetAQuotePage from "./components/pages/GetAQuotePage";
import AboutUsPage from "./components/pages/AboutUsPage";
import ContactUsPage from "./components/pages/ContactUsPage";
function App() {
return (
<ThemeProvider theme={appTheme}>
<Header />
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/services" element={<ServicesPage />} />
<Route path="/projects" element={<ProjectsPage />} />
<Route path="/aboutus" element={<AboutUsPage />} />
<Route path="/contactus" element={<ContactUsPage />} />
<Route path="/getaquote" element={<GetAQuotePage />} />
</Routes>
</ThemeProvider>
);
}
export default App;
I tried applying textColor and indicatorColor to Tabs, and its kinda somehow shows the tab text but ripple effect changes to double click. Also ripple effect on tab changes to double click as soon as I add active tab effect.

I make mistakes in Next js, but I dont know where

I use Next js dont correct, but I dont understend why. I saw github repository other programers, but I dont see where I made mistakes. That I make mistakes tolt me employer. The only one differences I found is I use only globals.css, but I think it dont mitakes. I want to grow as a programer, but I cant become better whisout your help. Please told me where i make mistakes in Next js.
My github repository: https://github.com/Yury11111111111/books-catalog
Code:
componets/BookComponent.js
import React from "react";
import Link from "next/link"
import Image from 'react-bootstrap/Image'
const BookComponent = (props) => {
return (
<>
<Link href={`/book/${props.book.id}`}>
<div className="book__wraper">
{props.book?.volumeInfo?.categories ?
<div className="book__category">{props.book?.volumeInfo?.categories[0]}</div>
: <></>}
{props.book?.volumeInfo?.imageLinks?.thumbnail ? (
<Image
src={props.book?.volumeInfo?.imageLinks?.thumbnail}
alt="book cover"
className="book__img"
/>
) : (
<Image className="noCover" src="https://rublevbar.com/files/rublevbar/image/no_product.jpg" alt="no book cover" />
)}
<div className="book__title">{props.book?.volumeInfo?.title}</div>
<div className="book__autors">{props.book?.volumeInfo?.authors}</div>
</div></Link>
</>
);
};
export default BookComponent;
pages/_app.js
import "../styles/globals.css";
import { store } from "../store";
import { Provider } from "react-redux";
import 'bootstrap/dist/css/bootstrap.min.css';
function MyApp({ Component, pageProps }) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
pages/index.js
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { fetchBooksData } from "../slices/booksSlice";
import Head from "next/head";
import { Container, Form, Row, Col, Button, InputGroup } from "react-bootstrap";
import BookComponent from "../componets/BookComponent";
export default function Home() {
const books = useSelector((state) => state.books.books);
const name = useSelector((state) => state.books.name);
const startIndex = useSelector((state) => state.books.startIndex);
const error = useSelector((state) => state.books.error);
const [resultName, setResultName] = useState("book");
const [resultStartIndex, setResultStartIndex] = useState(0);
const [resultCategory, setResultCategory] = useState("all");
const [resultSort, setResultSort] = useState("relevance");
const dispatch = useDispatch();
useEffect(() => {
dispatch(
fetchBooksData({
name: resultName,
startIndex: resultStartIndex,
category: resultCategory,
sort: resultSort,
})
);
}, [resultName, resultStartIndex, resultCategory, resultSort, dispatch]);
if (error === "error") {
dispatch(
fetchBooksData({
name: resultName,
startIndex: resultStartIndex,
category: resultCategory,
sort: resultSort,
})
);
}
function categoryChange() {
setResultCategory(document.querySelector("#category").value);
setResultStartIndex(0);
dispatch(
fetchBooksData({
name: resultName,
startIndex: resultStartIndex,
category: resultCategory,
sort: resultSort,
})
);
}
function sortChange() {
setResultSort(document.querySelector("#sort").value);
setResultStartIndex(0);
dispatch(
fetchBooksData({
name: resultName,
startIndex: resultStartIndex,
category: resultCategory,
sort: resultSort,
})
);
}
function handleSubmit() {
const input = document.querySelector("#form");
setResultName(input.value);
}
function go_back() {
setResultStartIndex(resultStartIndex - 30);
}
function go_forward() {
setResultStartIndex(resultStartIndex + 30);
}
function handleKeyPress(e) {
if (e.charCode == 13) {
e.preventDefault()
const input = document.querySelector("#form");
setResultName(input.value);
}
}
return (
<>
<Head>
<title>Books catalog</title>
</Head>
<div id="page-preloader" className="preloader">
<div className="loader"></div>
</div>
<header className="header">
<Container>
<h1 className="title">Search for books</h1>
<Form>
<Row className="justify-content-center">
<Col xl={6}>
<InputGroup>
<Form.Control
onKeyPress={handleKeyPress}
id="form"
placeholder="Search books"
/>
<Button type="button" onClick={handleSubmit}>
Search
</Button>
</InputGroup>
</Col>
</Row>
<Row className="mt-3 justify-content-center">
<Col xl={3}>
<Form.Select
onChange={categoryChange}
id="category"
aria-label="Default select example"
>
<option value="all">all</option>
<option value="art">art</option>
<option value="biography">biography</option>
<option value="computers">computers</option>
<option value="history">history</option>
<option value="medical">medical</option>
<option value="poetry">poetry</option>
</Form.Select>
</Col>
<Col xl={3}>
<Form.Select
onChange={sortChange}
id="sort"
aria-label="Default select example"
>
<option value="relevance ">relevance </option>
<option value="newest">newest</option>
</Form.Select>
</Col>
</Row>
</Form>
</Container>
</header>
<Container>Всего книг по вашему запросу: {books.totalItems}</Container>
<Container>
<div className="books">
{books.items?.map((book, index) => {
return <BookComponent book={book} key={index} />;
})}
</div>
</Container>
<footer>
{resultStartIndex !== 0 ? (
<Button className="go_back" onClick={go_back}>
go back
</Button>
) : (
<></>
)}
{books.totalItems > resultStartIndex ? (
<Button className="go_forward" onClick={go_forward}>
go forward
</Button>
) : (
<></>
)}
</footer>
</>
);
}
pages/book/[id].js
import React, { useState, useEffect } from "react";
import Link from "next/link";
import { Button, Container, Image, Row, Col } from "react-bootstrap";
import { useSelector, useDispatch } from "react-redux";
import { fetchThisBookData } from "../../slices/thisBookSlice";
import { useRouter } from "next/router";
export default function bookId() {
const router = useRouter();
const book = useSelector((state) => state.thisBook.thisBook);
const error = useSelector((state) => state.thisBook.error);
const dispatch = useDispatch();
useEffect(() => {
dispatch(
fetchThisBookData({
id: router.query.id,
})
);
}, [dispatch, router]);
if (error === "error") {
dispatch(
fetchThisBookData({
id: router.query.id,
})
);
}
console.log(book);
return (
<div>
<Container>
<div id="page-preloader" className="preloader">
<div className="loader"></div>
</div>
<Link href={"/"} className="back">
<Button className="back">Back</Button>
</Link>
<Row className="justify-content-center">
<Col>
<h1 className="this_book__title">{book?.volumeInfo?.title}</h1>
</Col>
</Row>
<Row>
<Col xl={6}>
<strong>Категории:</strong>
{book?.volumeInfo?.categories ? (
<div className="this_book__category">
{book?.volumeInfo?.categories}
</div>
) : (
<div>Нет категорий</div>
)}
<div className="this_book__autors">
<strong>
{book?.volumeInfo?.authors.length === 1 ? (
<>Автор </>
) : (
<>Авторы: </>
)}
</strong>
{book?.volumeInfo?.authors}
</div>
<br />
</Col>
<Col xl={6}>
{book?.volumeInfo?.imageLinks?.extraLarge ? (
<Image
src={book?.volumeInfo?.imageLinks?.extraLarge}
alt="book cover"
className="this_book__img"
/>
) : (
<Image
className="noCover"
src="https://rublevbar.com/files/rublevbar/image/no_product.jpg"
alt="no book cover"
/>
)}
</Col>
</Row>
</Container>
</div>
);
}
slices/booksSlice.js
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
const initialState = {
books: [],
status: null,
error: null,
};
export const fetchBooksData = createAsyncThunk(
"books/fetchData",
async function (state) {
const response = await fetch(
`https://www.googleapis.com/books/v1/volumes?q=${state.name}+${state.category}&startIndex=${state.startIndex}&maxResults=30&orderBy=${state.sort}`
);
const data = await response.json();
return data;
}
);
export const booksSlice = createSlice({
name: "books",
initialState,
extraReducers: {
[fetchBooksData.pending]: (state) => {
state.status = "loading";
state.error = null;
const preloader = document.querySelector("#page-preloader");
if (preloader.classList.contains("done")) {
preloader.classList.remove("done");
}
},
[fetchBooksData.fulfilled]: (state, action) => {
state.status = "resolved";
state.error = null;
state.books = action.payload;
const preloader = document.querySelector("#page-preloader");
if (!preloader.classList.contains("done")) {
preloader.classList.add("done");
}
},
[fetchBooksData.rejected]: (state) => {
state.error = "error";
console.log("Error");
},
},
});
export default booksSlice.reducer;
slices/thisBookSlice.js
import { createSlice, createAsyncThunk } from "#reduxjs/toolkit";
const initialState = {
thisBook: [],
status: null,
error: null,
};
export const fetchThisBookData = createAsyncThunk(
"books/fetchThisData",
async function (state) {
const response = await fetch(
`https://www.googleapis.com/books/v1/volumes/${state.id}`
);
const data = await response.json();
return data;
}
);
export const thisBookSlice = createSlice({
name: "book",
initialState,
extraReducers: {
[fetchThisBookData.pending]: (state) => {
state.status = "loading";
state.error = null;
const preloader = document.querySelector("#page-preloader");
if (preloader.classList.contains("done")) {
preloader.classList.remove("done");
}
},
[fetchThisBookData.fulfilled]: (state, action) => {
state.status = "resolved";
state.error = null;
state.thisBook = action.payload;
const preloader = document.querySelector("#page-preloader");
if (!preloader.classList.contains("done")) {
preloader.classList.add("done");
}
},
[fetchThisBookData.rejected]: (state) => {
state.error = "error";
console.log("Error");
},
},
});
export default thisBookSlice.reducer;

Having trouble routing to next page after button click

Need help routing to another page. I have page that enter user profile to firestore database and once Submit page will route to next page (WelcomePage.jsx).
Adding to Firestore database is working fine but the routing to next page is failing after click on the submiting button. I don't receive any error in the console log.
Below are my coding:
ProfilePage.jsx
import React,{useState} from 'react'
import {auth} from '../firebaseconfig';
import { person,calendarNumber,location} from 'ionicons/icons';
import '../components/stylesheet.css';
import {IonContent,IonPage,IonLabel,IonCard,IonList,IonItem,IonIcon,
IonInput,IonButton,IonHeader,IonToolbar,IonTitle,IonSelect,IonSelectOption } from '#ionic/react';
import { useAuth } from '../auth';
import { firestore } from '../firebaseconfig';
import { useForm } from 'react-hook-form';
import * as Yup from 'yup';
import { yupResolver } from '#hookform/resolvers/yup';
import WelcomePage from './WelcomePage';
import { Redirect } from 'react-router';
export default function ProfilePage(){
const { loggedIn } = useAuth();
const validationSchema = Yup.object().shape({
fullname: Yup.string()
.required('Enter Name'),
age: Yup.string()
.required('Enter Age'),
gender: Yup.string()
.required('Select Gender'),
location: Yup.string()
.required('Enter Location')
});
const formOptions = {resolver: yupResolver(validationSchema)}
const { register, handleSubmit, reset, formState } = useForm(formOptions);
const { errors } = formState;
const [patName, setPatName]=useState('');
const [patAge, setPatAge]=useState('');
const [patGender, setPatGender]=useState('');
const [patLocation, setPatLocation]=useState('');
const patPhoneNumber = auth.currentUser.phoneNumber.toString();
// const handleSave = async () => {
// const userData = {patAge, patName, patGender,patLocation,patPhoneNumber};
// const usersRef = firestore.collection('pat_profile').doc(auth.currentUser.uid).set({userData});
// };
const onSubmit = (data, e) => {
const {fullname,age,gender,location}= data;
const userData = {fullname,age,gender,location,patPhoneNumber};
firestore.collection('pat_profile').doc(auth.currentUser.uid).set({fullname,age,gender,location,patPhoneNumber});
return <Redirect to= "WelcomePage" />;
};
const onError = (errors, e) => console.log(errors, e);
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle className="profileheader">Profile Details</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding ion-content">
<form onSubmit={handleSubmit(onSubmit, onError)}>
<IonCard className="card-profile">
<IonList>
<IonItem className="item-background-color item-text">
<IonInput autofocus name="fullname"
placeholder="Enter Name" required {...register("fullname")}
value={patName} onIonChange={(event) => setPatName(event.detail.value)}
/>
<IonIcon icon={person} />
</IonItem>
</IonList>
<IonList>
<IonItem className="item-background-color item-text">
<IonInput type="number" required name="age"
placeholder="Age" {...register("age")}
value={patAge} onIonChange={(event) => setPatAge(event.detail.value)}
/>
<IonIcon icon={calendarNumber} />
</IonItem>
</IonList>
<IonList>
<IonItem className="item-background-color item-text">
<IonLabel>Gender</IonLabel>
<IonSelect required placeholder="Select" value={patGender} interface="popover" name="gender" {...register("gender")}
onIonChange={(event) => setPatGender(event.detail.value)}>
<IonSelectOption value="Female">Female</IonSelectOption>
<IonSelectOption value="Male">Male</IonSelectOption>
</IonSelect>
</IonItem>
</IonList>
<IonList lines="none">
<IonItem className="item-background-color item-text">
<IonInput
placeholder="Location" required {...register("location")} name="location"
value={patLocation} onIonChange={(event) => setPatLocation(event.detail.value)}
/>
<IonIcon icon={location} />
</IonItem>
</IonList>
</IonCard>
<IonButton className="item-button-reg ion-color-button" size="default" expand="block" type="submit" > REGISTER</IonButton>
</form>
</IonContent>
</IonPage>
);
}
WelcomePage.jsx
import React from "react";
import {auth} from '../firebaseconfig';
import { person,calendarNumber,location} from 'ionicons/icons';
import '../components/stylesheet.css';
import {IonContent,IonPage,IonLabel,IonCard,IonList,IonItem,IonIcon,
IonInput,IonButton,IonHeader,IonToolbar,IonTitle,IonSelect,IonSelectOption } from '#ionic/react';
export default function WelcomePage(){
return(
<IonPage>
<IonContent className="ion-padding phreg-content">
<IonLabel>Welcome</IonLabel>
</IonContent>
</IonPage>
);
}
I think.. may be you have problem or grammar error.
First, exist WelcomePage path in Route?
<Route path="/WelcomePage" component={WelcomePage}/>
And, Why don't you use <Router /> ?
example these.
<Router>
<Switch>
<PrivateRoute exact path="/" component={Home} />
<Route path="/users/sign_in" component={SingIn}/>
<Route path="/users/sign_up" component={SignUp}/>
</Switch>
</Router>
Or use this.
<Redirect to={{
pathname: '/WelcomePage'
}}/>

How can I override the user-select: none in RadioButton and CheckBox control labels?

Currently for pre 1.0.0 releases Material-UI does not allow text selection on RadioButton and Checkbox control labels.
How can I override this behavior? Apparently passing labelStyle={{ userSelect: 'all' }} to the component doesn't help.
What I'm trying to achieve is being able to highlight the text in the option label as per this screenshot:
You need to override the CSS class that prevents selection of the labels.
The labels are made with components of type FormControlLabel. At the bottom of the doc page for that component, you can see that the CSS label class is available to override.
So, you need to override the label class on each FormControlLabel like this:
// Define the overriding style
const styles = () => ({
selectableLabel: {
userSelect: 'all',
},
});
// Override the label CSS that prevents selection
<FormControlLabel classes={{ label: classes.selectableLabel }} value="male" control={<Radio />} label="Male" />
Here's full code for a group of selectable radio buttons (derived from the Radio buttons example in the docs:
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Radio, { RadioGroup } from 'material-ui/Radio';
import { FormLabel, FormControl, FormControlLabel } from 'material-ui/Form';
const styles = theme => ({
root: {
display: 'flex',
},
formControl: {
margin: theme.spacing.unit * 3,
},
group: {
margin: `${theme.spacing.unit}px 0`,
},
selectableLabel: {
userSelect: 'all',
},
});
class RadioButtonsGroup extends React.Component {
state = {
value: '',
};
handleChange = (event, value) => {
this.setState({ value });
};
render() {
const { classes } = this.props;
return (
<div className={classes.root}>
<FormControl component="fieldset" required className={classes.formControl}>
<FormLabel component="legend">Gender</FormLabel>
<RadioGroup
aria-label="gender"
name="gender1"
className={classes.group}
value={this.state.value}
onChange={this.handleChange}
>
<FormControlLabel classes={{ label: classes.selectableLabel }} value="male" control={<Radio />} label="Male" />
<FormControlLabel classes={{ label: classes.selectableLabel }} value="female" control={<Radio />} label="Female" />
<FormControlLabel classes={{ label: classes.selectableLabel }} value="other" control={<Radio />} label="Other" />
<FormControlLabel classes={{ label: classes.selectableLabel }} value="disabled" disabled control={<Radio />} label="Disabled" />
</RadioGroup>
</FormControl>
</div>
);
}
}
RadioButtonsGroup.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(RadioButtonsGroup);
And here's the full code for the Checkbox buttons (derived from the Checkboxes example in the doc):
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import { FormControl, FormGroup, FormControlLabel } from 'material-ui/Form';
import Checkbox from 'material-ui/Checkbox';
const styles = {
selectableLabel: {
userSelect: 'all',
},
};
class CheckboxesGroup extends React.Component {
state = {
gilad: true,
jason: false,
antoine: true,
};
handleChange = name => (event, checked) => {
this.setState({ [name]: checked });
};
render() {
const { classes } = this.props;
return (
<FormControl component="fieldset">
<FormGroup>
<FormControlLabel
classes={{ label: classes.selectableLabel }}
control={
<Checkbox
checked={this.state.gilad}
onChange={this.handleChange('gilad')}
value="gilad"
/>
}
label="Gilad Gray"
/>
<FormControlLabel
classes={{ label: classes.selectableLabel }}
control={
<Checkbox
checked={this.state.jason}
onChange={this.handleChange('jason')}
value="jason"
/>
}
label="Jason Killian"
/>
</FormGroup>
</FormControl>
);
}
}
CheckboxesGroup.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(CheckboxesGroup);