How to set a radiobutton checked by default in react native? - reactjs

how can I set a default checked radiobutton in react native? I'm trying to have a radio button already activated when the user enters the screen. Thanks for your help. II lready read that I have to use the value prop, but I do not now where to place it correctly, so that its working.
render(){
return (
<form>
<View>
<label>
<input
type="radio"
name="category"
value="anfaenger"
checked={this.state.selectedOption === "anfaenger"}
onChange={this.onValueChange}
/>
Anfänger
</label>
</View>
<View style={{marginTop:10}}>
<label>
<input
type="radio"
name="category"
value="geuebt"
checked={this.state.selectedOption === "geuebt"}
onChange={this.onValueChange}
/>
Geübt
</label>
</View>
<View style={{marginTop:10}}>
<label>
<input
type="radio"
name="category"
value="eingeschraenkt"
checked={this.state.selectedOption === "eingeschraenkt"}
onChange={this.onValueChange}
/>
Eingeschränkt
</label>
</View>
</form>
</View>
<View style={{magrinTop:'40'}}>
<button className="btn btn-default" type="submit">
Sichere Auswahl
</button>
<Button title="Erstelle meinen Plan" onPress={() => this.props.navigation.navigate('Uebungen', {
category: this.state.selectedOption,
}) }/>
</View>
</ScrollView>
</View>
);
}
}

You can pass a defaultChecked prop to a radio button component like so
export default function App() {
return (
<form>
<View>
<label>
<input
type="radio"
name="category"
value="anfaenger"
onChange={this.onValueChange}
defaultChecked
/>
Anfanger
</label>
</View>
<View style={{ marginTop: 10 }}>
<label>
<input
type="radio"
name="category"
value="geuebt"
onChange={this.onValueChange}
/>
Geubt
</label>
</View>
<View style={{ marginTop: 10 }}>
<label>
<input
type="radio"
name="category"
value="eingeschraenkt"
onChange={this.onValueChange}
/>
Eingeschrnkt
</label>
</View>
</form>
);
}
The value prop is passed on to the next page when the form is submitted. So if the first option is selected, 'anfaenger' will appear in the form results.
Edit:
You're right, the defaultChecked prop is only compatible with Web devices, not iOS and Android devices. When running on iOS and Android, I also noticed that some of the tags you used aren't compatible with React-Native, such as <forms>, <input>, <label>, unless there is a library that supports this. However, I wasn't able to find a library where you could import these components from.
Here is an Expo Snack I made that holds some code for radio buttons (styling need a bit of work, but maybe you can find a better UI library other than react-native-paper).
Basically, I set my React Hook's initial state to the first option in the form. This means that when the user opens the form, the first option should always be checked, since that is the state of the Hook.
If in fact your code does work as originally posted, I'd recommend setting your components selectedOption state variable to one of the options in the form.
state = {
selectedOption: 'anfaenger', // or 'geuebt' or 'eingeschraenkt' or any value you want to be the default
}
That way, when it checks for the state being a value in the radio button's status, it will be met and marked. However, if you need selectedOption to initialize to some value other than those in the radio buttons, then you can do boolean logic like so:
(Assuming selectedOption initializes to '' a.k.a empty string):
checked={this.state.selectedOption === "" || this.state.selectedOption === "anfaenger"}

Related

How do I use the SpeedDial to upload a file?

(this seem to have been asked previously but I couldn't find any hint on if it was actually answered)
MUI has a good demo for creating upload buttons which boils down to:
<input accept="image/*" className={classes.input} id="icon-button-file" type="file" />
<label htmlFor="icon-button-file">
<IconButton color="primary" aria-label="upload picture" component="span">
<PhotoCamera />
</IconButton>
</label>
What I wonder is how to implement the same using the Speed Dial. Inherently the SpeedDialAction seems to materialize as a <button/>, but it's not possible to e.g. wrap the SpeedDialAction in a <label htmlFor /> as its parent will try to set some props on it and will fail.
So how do I initiate the file selection from within the Speed Dial or a FAB in general?
You can create a wrapper component that forwards props to SpeedDialAction.
function UploadSpeedDialAction(props) {
return (
<React.Fragment>
<input
accept="image/*"
style={{ display: "none" }}
id="icon-button-file"
type="file"
/>
<label htmlFor="icon-button-file">
<SpeedDialAction
icon={<CloudUploadIcon />}
tooltipTitle="upload"
component="span"
{...props}
></SpeedDialAction>
</label>
</React.Fragment>
);
}
https://codesandbox.io/s/material-demo-forked-h6s4l
(Note to future readers: For v5, time allowing, we hope to rationalise where props rather than context are used to control children, in order to solve exactly this kind of issue. So check whether this solution is still needed.)
It is - in my knowledge - not possible to add the htmlFor in any way. So what I would do is to add a hidden input type file and then add a ref to it. Then in the onclick of the SpeedDialAction button I would call a handler function that clicks on the input ref. Like this:
const inputRef = useRef();
const handleFileUploadClick = () => {
inputRef.current.click();
};
Then your SpeedDialAction:
<SpeedDialAction
onClick={handleFileUploadClick}
... the rest of your props
/>
And then finnaly your actual input:
<input
style={{ display: "none" }}
ref={inputRef}
accept="image/*"
id="contained-button-file"
multiple
type="file"
/>
Working demo: https://codesandbox.io/s/material-demo-forked-f9i6q?file=/demo.tsx:1691-1868

Conditionally remember radio button selection in React

I am creating a modal to filter for profiles, on react-bootstrap and redux.
I need to filter to remember it's previous selection every time the user reopen it, even if he returns from another page. It works fine with value based components, such as "range slider" or "text search" because I can grab the previous saved redux store and plug into the component's attribute, such as:
value={rangeValue}
But for radio buttons, I am not sure since the attribute itself, "checked", is its own value.
<Form.Check
inline
label="male"
name="male"
checked <-----------
onChange={(e) => onRadioChange(e)}
/>
I want it to show "checked" only if the user has previously done so. I already have the user choice (whether checked or not) saved in my store, but don't know how to plug it in conditionally.
The returned JSX below
import React, { useState } from "react";
import { Form, Button } from "react-bootstrap";
...
<Form>
<div className="form_content_wrap">
<Form.Group>
<Form.Label htmlFor="formControlRange">Age: {rangeValue}</Form.Label>
<Form.Control
type="range"
className="form-control-range"
id="formControlRange"
min="0"
max="100"
value={rangeValue}
onChange={(e) => setRangeValue(e.currentTarget.value)}
/>
</Form.Group>
<Form.Group>
<Form.Label htmlFor="formControlRange">Gender: </Form.Label>
<Form.Check
inline
label="female"
name="female"
onChange={(e) => onRadioChange(e)}
/>
<Form.Check
inline
label="male"
name="male"
checked <<<------- THIS IS WHERE I WANT TO CHANGE
onChange={(e) => onRadioChange(e)}
/>
</Form.Group>
<Form.Group>
<Form.Label>Keyword</Form.Label>
<Form.Control
type="text"
placeholder="search description"
value={descValue}
onChange={(e) => setDescValue(e.currentTarget.value)}
/>
</Form.Group>
<Button
variant="primary"
type="submit"
onClick={onFormSubmit}
style={{ marginRight: "10px" }}
>
Submit
</Button>
<Button variant="primary" type="submit" onClick={onFormClear}>
Clear
</Button>[enter image description here][1]
</div>
</Form>
Thanks
React appears to be smart enough automatically remove the attribute if you set it equal to a Javascript expression that is not truthy. You should be able to just pull this state from your store. See this question for more details.
<Form.Check checked={true} />
<Form.Check checked={false} />

Radio buttons in a Semantic UI React table retain checked attribute after selecting another radio button in the same row?

My radio buttons have the same name so the behavior I would expect is to:
select a radio button
see that it has the checked attribute
select a different radio button in the same row, and then
see that it has the checked attribute while the first one no longer does.
Instead:
I click a radio button
see that it is checked
click a different one, and
the UI shows that the first one is no longer checked but it retains the checked attribute when I inspect the source.
Why are these radio buttons not fully interacting with each other?
<Form onSubmit={(e) => { handleAnswerFormSubmit(e) }}>
<Table celled>
<Table.Body>
<Table.Row>
<Table.Cell>
airplane
</Table.Cell>
<Table.Cell>
<Radio name="airplane" value="1" />
</Table.Cell>
<Table.Cell>
<Radio name="airplane" value="2" />
</Table.Cell>
<Table.Cell>
<Radio name="airplane" value="3" />
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
<Form.Button>Continue</Form.Button>
</Form>
I think what you are looking for is Radio group. The following example, also available on Semantic UI React Docs will help you. Here goes the code:
export default class RadioExampleRadioGroup extends Component {
state = {}
handleChange = (e, { value }) => this.setState({ value })
render() {
return (
<Form>
<Form.Field>
Selected value: <b>{this.state.value}</b>
</Form.Field>
<Form.Field>
<Radio
label='Choose this'
name='radioGroup'
value='this'
checked={this.state.value === 'this'}
onChange={this.handleChange}
/>
</Form.Field>
<Form.Field>
<Radio
label='Or that'
name='radioGroup'
value='that'
checked={this.state.value === 'that'}
onChange={this.handleChange}
/>
</Form.Field>
</Form>
)
}
}

Dynamically rendering Custom Radio Button Component

I am trying to dynamically render a custom button component in a form in react js.
Here is my radio custom button component.
export class CustomRadio extends Component {
render() {
return (
<div>
<FormGroup>
<ControlLabel>{this.props.label}</ControlLabel>
<br />
<input type="radio" name={this.props.name} />
</FormGroup>
</div>
);
}
}
The below is how I call that component in a form
<CustomRadio label="status" />
Anyways I was not able to get the expected output. Can anyone help me out to solve this matter?
First thing, you must import your component as,
import {CustomRadio} from './CustomRadio'; //because you are exporting as named export
Another thing, as you are using this.props.name you must pass it as,
<CustomRadio label="Status" name="name"/>
By looking at FormGroup, I think you are using reactstrap, in reactstrap you can use this to get radio button,
<FormGroup>
<Label>
<input type="radio" name={this.props.name} />
{this.props.label}
</Label>
</FormGroup>
Demo
Note:
If ControlLabel is another custom component, then you can do this,
<FormGroup>
<ControlLabel>
<input type="radio" name={this.props.name} />
{this.props.label}
</ControlLabel>
</FormGroup>
And your ControlLabel component should be,
const ControlLabel = (props) => {
return (
<Label>{props.children}</Label>
)
}
As you have mentioned the name as a prop in CustomRadio component you must need to pass name also from here as follows:
<CustomRadio label="status" name="Xyz" />

Validating Office fabric react textfield

I have a page with bunch of office fabric textField controls. They have their own onGetErrorMessage method to validate and show the error message. But I don't want to fire validation onBlur or onFocusIn. I want to validate all on some 'Save' button click. How can I access the controls and walk through those and fire validation on it at once? The controls are not in tag.
e.g.
<div>
<div>
<TextField label="First Name:" onGetErrorMessage={this._onError} />
</div>
<div>
<TextField label="Last Name:" onGetErrorMessage={this._onError} />
</div>
<div>
<TextField label="Email:" onGetErrorMessage={this._onError} />
</div>
<div>
<TextField label="Username:" onGetErrorMessage={this._onError} />
</div>
<div>
<input type="button" onClick={this.validate()} value="Save" />
</div>
</div>
I tried initializing TextField first and then using it in render() and accessing it in validate() but didn't work. Any ideas how this can be achieved?
Just came across this, but looks like no one answered.
Can be done via a simple event capturing:
validate = () =>{
this.go = true;
}
_onError = () => {
if (!this.go){
return "";
}
}

Resources