How to make smaller radio buttons - reactjs

I can't find a way to create a group of three small (19px high) labelled radio buttons in material-ui. I'm migrating a browser app from static HTML/JS into material-ui/react, and I need the group to stay the same size.
The button group I'm starting with has three small vertically aligned labelled radio buttons. Here's
a screenshot:
Here's the code for the best I've been able to do using the material-ui documentation:
<FormControl
margin="dense"
size="small"
>
<RadioGroup
size="small"
name="dataSource"
value={dataSource}
onChange={handleDataSourceChange}
>
<FormControlLabel
value="CaseCount"
control={
<Radio
className={classes.radio}
size="small"
/>
}
label="Cases"
/>
<FormControlLabel
value="DeathCount"
control={
<Radio
className={classes.radio}
size="small"
/>
}
label="Deaths"
/>
<FormControlLabel
value="HotSpots"
control={
<Radio
size="small"
/>
}
label="HotSpot warning"
/>
</RadioGroup>
</FormControl>
This results in an oversized group -- the button icons are too large, the text is too large, and each row is 38 pixels high (twice the 19 pixels of the original). Here's a screenshot of the material-ui counterpart:
I think I want the result to use a vanilla html input (with type of radio) instead of an svg icon, and a font with font-height of 13px. How do I do that in material-ui?
I know how to fix the padding-left so I'm not worried about that. How do I get rows that are 19px high instead of 38px?

Reason
If you inspect the Material radio button, we can see that the padding of the radio button is causing each row to have a height of 38px.
Code
Therefore, we can simply remove the vertical padding from all radio buttons with the following code (note that my code is slightly different than yours):
const useStyles = makeStyles({
// Applied to <Radio />
root: {
width: 19,
height: 19,
paddingTop: 0,
paddingBottom: 0,
},
// Applied to <FormControlLabel />
label: {
fontSize: 13
}
});
export default function RadioButtonsGroup() {
const [value, setValue] = React.useState("CaseCount");
const classes = useStyles();
const handleChange = (event) => {
setValue(event.target.value);
};
const customRadio = <Radio size="small" classes={{root: classes.root}} />;
return (
<FormControl component="fieldset">
<RadioGroup value={value} onChange={handleChange}>
<FormControlLabel classes={{label: classes.label}} control={customRadio} value="CaseCount" label="Cases" />
<FormControlLabel classes={{label: classes.label}} control={customRadio} value="DeathCount" label="Deaths" />
<FormControlLabel
classes={{label: classes.label}}
control={customRadio}
value="HotSpots"
label="Hotspot Warning"
/>
</RadioGroup>
</FormControl>
);
}
Explanation
According to the Radio API documentation, we can apply custom styling to root of the radio button by overriding styles with classes using the class name of root. Therefore, we first define a style object called root in the makeStyles() function. Next, we apply the styling to the Radio component by adding the prop of classes={{root: classes.root}}:
<Radio size="small" classes={{root: classes.root}} />
Similarly, according to the FormControlLabel API documentation, we can apply custom styling to the text label using the label class name. Therefore, we first define a style object of label in the makeStyles() function. Next, we apply the styling to the FormControlLabel component by adding the prop of classes={{label: classes.label}}:
<FormControlLabel classes={{label: classes.label}} /* ... */ />

Related

How can I manually set accordion close on button

I am completely new to React. Here is the code I currently have. I removed some unnecessary parts to keep it clean.
<AccordionSummary
expandIcon={}
aria-controls="panel1a-content"
>This is Accordian
<AccordionSummary/>
<AccordionDetails>
<Grid container spacing={4} mb={5}>
<Grid item xs={12} md={6}>
<FormControl>
<RadioGroup
aria-labelledby="demo-controlled-radio-buttons-group"
name="controlled-radio-buttons-group"
value={value}
onChange={handleChange}
>
<FormControlLabel
value="yes"
name="Yes"
control={<Radio onChange={handleChange} />}
label="Yes"
/>
<FormControlLabel
value="no"
name="No"
control={<Radio onChange={handleChange} />}
label="No"
/>
</RadioGroup>
</FormControl>
</Grid>
</Grid>
<Grid>
<Button className={classes.button_dark} variant="contained">
Submit
</Button>
<Button className={classes.button_light}>Cancel</Button>
</Grid>
</AccordionDetails>
I was using controlled accordion where I want a change, but I tried various combinations referring MUI docx, but I'm not getting any soln. This is the states I have used, but this one is for a radio button.
const [value, setValue] = React.useState("");
const handleChange = (e) => {
const {value} = e.target;
setValue(value);
};
What I want is that whenever I click the cancel button, the accordion should hide. The expand icon is working, but here I want to hide the accordion whenever I press the cancel button.
In MUI Accordion there's a property called expanded which accepts a boolean value and using that you can manually control the expansion and hide the according. You need to maintain a state to do that. Here's a basic example.
const [expanded, setExpanded] = React.useState();
<Accordion expanded={expanded === 'panel1'} onChange={() => setExpanded('panel1')}>
// items inside the accordion
<Button className={classes.button_light} onClick={() => setExpanded(undefined)}>Cancel</Button>
</Accordion>
This is just a simple solution to your problem.
refer to this for more details
Update
Here's a working example

React MUI DesktopDatePicker behaves as refocusing on every click

Given the following code:
const DatePeacker = () =>{
return (
<LocalizationProvider dateAdapter={AdapterMoment}>
<Stack spacing={3}>
<DesktopDatePicker
label="Día de publicación"
inputFormat="DD/MM/yyyy"
value={fechavalor}
onChange={handleDatepicker}
renderInput={(params) => <TextField required size="small" color="primary" style = {{width: 300}} {...params} inputProps={{ ...params.inputProps, placeholder: "dd/mm/aaaa" }} />}
/>
</Stack>
</LocalizationProvider>
)}
The following behaviour on the DatePicker label occurs on clicking outside it or in different elements,either click an option of a select or writing in the textfield (which has a function to capitalize new words. It does not happen when clicking outside the component. May it be cause by reloading the value of the datepicker for some reason?
I leave here the handleDatePicker function:
const handleDatepicker = (newvalue)=>{setFechavalor(newvalue);}

Can't get TreeView Icons and IconButton for Tests

I'm trying to test a component that has an endAdornment IconButton and other with a TreeView, but neither the IconButton and the ExpandIcon/CollapseIcon have good options to dispatch test events.
This is the TextField component that I'm using:
<TextField
fullWidth
label="Label"
onChange={handleChange}
type="text"
InputProps={{
endAdornment: (
<InputAdornment >
<IconButton onClick={openAssetHierarchy}>
<Folder />
</IconButton>
</InputAdornment>
),
}}
/>
This is the TreeView component:
<TreeView
defaultCollapseIcon={<ArrowDropDown />}
defaultExpandIcon={<ArrowRight />}
defaultEndIcon={<div style={{ width: 24 }} />}
onNodeToggle={handleToggle}
onNodeSelect={handleSelect}
>
[...]
</TreeView>
For the TextField icon button:
For TreeView when using Testing Playground to get the icon
There aren't good queries to get the icons for tests. How can I get these options?
For the IconButton you can add an aria-label attribute to the element, then use getByLabelText to access it in your test. This is also useful and recommended for accessibility purposes.
<IconButton aria-label="add a file" onClick={openAssetHierarchy}>
<Folder />
</IconButton>
screen.getByLabelText('add a file') // Gets you the `IconButton`
For the TreeView items, I assume you don't actually need to access the icon specifically but simply need to access the TreeItem for testing purposes. This can be done with getByRole and passing the tree item's name.
screen.getByRole('treeitem', { name: /Test1/ }) // Gets you the first `TreeItem`

Cannot get Material UI radio buttons to work with Formik

I am trying to use Material UI radio buttons with Formik, and they are not clicking properly. I've reduced the problem to the following example: https://codesandbox.io/s/amazing-currying-s5vn0
If anyone knows what I might be doing wrong, or if there is a bug in either system, then please let me know. When clicking on the buttons in the above example, they do not stay clicked. I have a more complex react functional component that uses other library components, so I cannot include it here. It is behaving a little differently: the buttons stay clicked even after clicking a different button. It may or may not be the same issue. Thanks in advance.
You need to be rendering the radio buttons inside of the FormikRadioGroup component you are rendering as a Formik Field. That way you can actually pass the props being managed by Formik down to the components to be used, as well as allow the RadioGroup component to make sure only one button is clicked at a time. I added an options prop to provide a way to pass an array of radio options and removed all of the elements you were rendering outside of that component:
const FormikRadioGroup = ({
field,
form: { touched, errors },
name,
options,
...props
}) => {
return (
<React.Fragment>
<RadioGroup {...field} {...props} name={name}>
{options.map(option => (
<FormControlLabel value={option} control={<Radio />} label={option} />
))}
</RadioGroup>
{touched[fieldName] && errors[fieldName] && (
<React.Fragment>{errors[fieldName]}</React.Fragment>
)}
</React.Fragment>
);
};
Fork here.
EDIT: Updated the sandbox with an alternate example using a render function as a child within the Field component.
import { FormControlLabel, Radio, LinearProgress } from '#material-ui/core';
import { Formik, Field } from 'formik';
import { RadioGroup } from 'formik-material-ui';
<Formik {...otherProps}>
{({ isSubmitting }) => (
<Field component={RadioGroup} name="activity">
<FormControlLabel
value="painting"
control={<Radio disabled={isSubmitting} />}
label="Painting"
disabled={isSubmitting}
/>
<FormControlLabel
value="drawing"
control={<Radio disabled={isSubmitting} />}
label="Drawing"
disabled={isSubmitting}
/>
<FormControlLabel
value="none"
control={<Radio disabled={isSubmitting} />}
label="None"
disabled
/>
</Field>
)}
</Formik>;
Now this is documented! Using RadioGroup from formik-material-ui.
https://stackworx.github.io/formik-material-ui/docs/api/material-ui/

Better way to generate a component array in a React reusable component

I am building a reusable component for radio buttons. Naturally, it is unpredictable to know how many radios it will be needed in each case, so some how that has to be mapped in an array. Also, the component needs to respect the HTMl structure that it will render in and the RadioGroup and Radio buttons must be in the same component for scope purposes.
I have it working this way:
Component
const CMRadioGroup = (props, context) => {
return (
<RadioGroup
name={props.name}
style={{flexDirection: "row"}}
className={props.className}
value={props.value}
onChange={props.onChange}>
{props.radios.map(radio =>
<FormControlLabel
key={radio.value}
value={radio.value}
style={{marginRight: 40, height:30}}
control={<Radio />}
label={context.t(radio.label)} />,
)}
</RadioGroup>
);
};
Usage
<CMRadioGroup
name="select"
value={this.state.select}
onChange={this.handleChangeSelect}
//I don't like the part below
radios={[
{
value:"radio1",
label:"My First Radio",
},
{
value:"radio2",
label:"My Second Radio",
},
]}/>
}
It would prefer if instead of using it as a json array, that they were functional items that can be propped with functions and other props such as colors, onChange, etc. Something like this for example:
<CMRadioGroup
name="select"
value={this.state.select}
onChange={this.handleChangeSelect}
//This is better
<Radio
color="primary"
value="radio1",
label="My First Radio"/>
<Radio
color="primary"
value="radio2",
label="My Second Radio"/>
...
<Radio
color="secondary"
value="radio-nth",
label="My Nth Radio"/>
]}/>
}
Thanks in advance guys
What I can interpret is you want to pass radio buttons as children to component. you can easilt pass them as a clild. See example.
<CMRadioGroup
name="select"
value={this.state.select}
onChange={this.handleChangeSelect}
>
<Radio
color="primary"
value="radio1",
label="My First Radio"/>
<Radio
color="primary"
value="radio2",
label="My Second Radio"/>
<Radio
color="secondary"
value="radio-nth",
label="My Nth Radio"/>
</CMRadioGroup>
Do not pass them as props. The only drawback of this approach is that the component will rerender everytime of state change as children are treated as objects and react shallow compares the props (when using React.PureComponent).

Resources