I want to get RadioButton attribute when the page first starts(ex: when first call componentWillMount()) I will compare this problem to JQuery.
$(function() {
var radioAttr = $('#radioButton_id').find("option:selected").val()
});
I want to implement the JQuery source to React Hooks. if you konw how, please help me..
const UserEdit = ({ classes, ...props }) => {
const types = [
{id:'INDIVIDUAL'},
{id:'COMPANY'}
];
const [ checked, setChecked ] = useState(true);
const onClickRadioBtn = (event,id) => {
(id === "COMPANY") ? setChecked(false) : setChecked(true)
};
useEffect(()=>{
**/* get radioButton attr */**
});
return(
<Edit {...props}>
<SimpleForm>
<TextInput source="username" validate={required()}/>
<TextInput source="email" validate={[required(),email()]}/>
<TextInput source="phoneNumber" validate={[required(),minLength(10),number()]}/>
<RadioButtonGroupInput label="Type"
source="userType"
choices={types}
optionText="id"
validate={required()}
onChange={onClickRadioBtn}
/>
{ !checked && (
<ReferenceInput label="Company" source="company.id" reference="companies" validate={required()}>
<SelectInput optionText="name"/>
</ReferenceInput>
)}
</SimpleForm>
</Edit>
);
};
Wrap RadioButtonGroupInput
in a div
and give that div
a ref
prop. We'll also create a new variable called nodes
, to store the element
const UserEdit = ({ classes, ...props }) => {
const nodes = {}
const types = [
{id:'INDIVIDUAL'},
{id:'COMPANY'}
];
const [ checked, setChecked ] = useState(true);
const onClickRadioBtn = (event,id) => {
(id === "COMPANY") ? setChecked(false) : setChecked(true)
};
useEffect(()=>{
//get the element we passed, our input will be the first child
let input = nodes.example.children[0] ? nodes.example.children[0] : null;
console.log(input.getAttribute("type"));
}, []);
return(
<Edit {...props}>
<SimpleForm>
<TextInput source="username" validate={required()}/>
<TextInput source="email" validate={[required(),email()]}/>
<TextInput source="phoneNumber" validate={[required(),minLength(10),number()]}/>
<div ref={elem => (nodes["example"] = elem)}>
<RadioButtonGroupInput label="Type"
source="userType"
choices={types}
optionText="id"
validate={required()}
onChange={onClickRadioBtn}
/>
</div>
{ !checked && (
<ReferenceInput label="Company" source="company.id" reference="companies" validate={required()}>
<SelectInput optionText="name"/>
</ReferenceInput>
)}
</SimpleForm>
</Edit>
);
};
Here's a sandbox for example: https://codesandbox.io/s/romantic-mcnulty-qqpbs