Reputation: 95
I'm currently confused, where a argument is coming from. Because for my understanding I don't implizite pass it anywhere.
Could someone maybe explain how to understand this example ? Thanks.
import React from 'react';
import FormatAlignLeftIcon from '@material-ui/icons/FormatAlignLeft';
import FormatAlignCenterIcon from '@material-ui/icons/FormatAlignCenter';
import FormatAlignRightIcon from '@material-ui/icons/FormatAlignRight';
import FormatAlignJustifyIcon from '@material-ui/icons/FormatAlignJustify';
import ToggleButton from '@material-ui/lab/ToggleButton';
import ToggleButtonGroup from '@material-ui/lab/ToggleButtonGroup';
export default function ToggleButtons() {
const [alignment, setAlignment] = React.useState('left');
const handleAlignment = (event, newAlignment) => {
setAlignment(newAlignment);
};
return (
<ToggleButtonGroup
value={alignment}
exclusive
onChange={handleAlignment}
aria-label="text alignment"
>
<ToggleButton value="left" aria-label="left aligned">
<FormatAlignLeftIcon />
</ToggleButton>
<ToggleButton value="center" aria-label="centered">
<FormatAlignCenterIcon />
</ToggleButton>
<ToggleButton value="right" aria-label="right aligned">
<FormatAlignRightIcon />
</ToggleButton>
<ToggleButton value="justify" aria-label="justified" disabled>
<FormatAlignJustifyIcon />
</ToggleButton>
</ToggleButtonGroup>
);
}
To narrow it further down: The newAlignment argument is the one that confuses me.
...
const handleAlignment = (event, newAlignment) => {
setAlignment(newAlignment);
};
...
Upvotes: 0
Views: 57
Reputation: 477
ToggleButtonGroup
component has an has a value
and an onChange
property. When the component changes, it passes it's event
and alignment
value to your handler that you provided; in this case handleAlignment
.
Upvotes: 0
Reputation: 20944
The ToggleButtonGroup
component handles this internally. It basically does something in a way of the example below. Note: this is pseudo code, not how it actually works.
const ToggleButtonGroup = ({ onChange, children }) => {
const handleInternalOnChange = event => {
const value = event.target.value;
onChange(event, value); // Both the event and the value is passed.
};
return (
<div onChange={handleInternalOnChange}>
{children}
</div>
)
};
So ToggleButtonGroup
wraps the onChange
function and handles the original event, getting the values from it, before passing both the event
and the value
to your onChange
handler.
Upvotes: 1