I'm trying to create a very simple radio button system within react but cannot get the radio buttons to render correctly. I have attached my code as well as what the output looks like. What can I do to get the radio buttons to properly show up? Thanks!
https://i.imgur.com/N0ik047.png
constructor (props) {
super(props);
var user = props.location.state;
this.state = {
selected: ''
};
}
onChange = e => {
this.setState({selected: e.target.value})
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<h1> Welcome! </h1>
<h4> Are you a: </h4>
<ul>
<li>
<label>
<input
type="radio"
value="student"
checked={value === "student"}
onChange={this.onChange}
/>
<h5> Student </h5>
</label>
</li>
<li>
<label>
<input
type="radio"
value="professor"
checked={value === "professor"}
onChange={this.onChange}
/>
<h5> Professor </h5>
</label>
</li>
</ul>
<button type="submit">Submit</button>
</form>
)
}
}
[1]: https://i.stack.imgur.com/DmU0W.png
There doesn't look to be anything wrong with the markup. I suspect that the styling is preventing the display of the radio buttons. On the image everything is centered - is it possible that the h5 header is rendering over the radio button. If you inspect the source of the web page and see the radio buttons in the DOM that indicates that styling is the issue.
Related
I'm controlling a Radio button on a react form.
The state is updating on change as expected, but the checked value isn't being rerendered on change. Therefore, from a user perspective the button isn't working.
I've replicated this in a codesandbox here https://codesandbox.io/s/eager-hertz-stzgk?file=/src/App.js
Relevant code:
const [selectedRole, setSelectedRole] = useState("staff");
...
const handleRoleChange = (event) => {
event.preventDefault();
setSelectedRole(event.target.value);
};
...
<form>
<label>
Staff
<input
type="radio"
name="role"
value="staff"
checked={selectedRole === "staff"}
onChange={handleRoleChange}
/>
</label>
<label>
Student
<input
type="radio"
name="role"
value="student"
checked={selectedRole === "student"}
onChange={handleRoleChange}
/>
</label>
</form>
Appreciate any help as I'm out of ideas.
Thank you
That is because of event.preventDefault() in 9th line which stops it to change it instantly
Edit 1: 2/5/2022:
you can also refer to: docs
Okay, so in my code, I have these two radio inputs, one with a fixed value, one with an input-field to take the dynamic value.
Now what I wanted to do is, when the user enters value in the input field, the corresponding radio button will get selected automatically, and the values will get updated as well. and if the user selects the default value, the state will get updated with the default value.
My code looks like this..
<ul className='list-unstyled mb-0 d-flex flex-column flex-lg-row justify-content-around'>
<li className='mr-4'>
<input
defaultChecked
onChange={() => updateState('timeLimit',defaultTime)}
type="radio"
value={defaultTime}
name='time'
className='mr-2'
id="defaultTime"/>
<label htmlFor="defaultTime"> {defaultTime} Mins. (default)</label>
</li>
<li>
<input
onChange={(e) => updateState('timeLimit',e.target.value)}
type="radio"
name='time'
value={customTime}
ref={customTimeRef}
className='mr-2'
id="customTime"/>
<label htmlFor="customTime">
<input
onChange={(e) => updateCustomTime(e.target.value)}
style={{outline:'none', border:'none',width:'9rem'}}
placeholder='Enter Your Time'
min='0'
className='border-bottom border-info pl-2 pb-1'
type="number"/> Mins. (custom)
</label>
</li>
</ul>
The functions are defined as
const updateCustomTime = (val) => {
if(customTimeRef.current.checked){
setCustomTime(val)
updateState('timeLiimit',val)
}
else{
customTimeRef.current.checked=true
setCustomTime(val)
updateState('timeLiimit',val)
}
}
Now the issue is, when I type into my input field, the updateState function is fired, the radio gets checked, but if I click on the radio buttons afterwards, they aren't firing the onchange events associated.
What's wrong here ? And how to achieve the desired result ??
Check this component
use a boolean state to set the checked property
const App = () => {
const [useDefault, setUseDefault] = React.useState(true)
return (
<div>
<div>
<input type="radio" name="time" checked={useDefault} onClick={() => setUseDefault(true)} />
</div>
<div>
<input type="radio" name="time" checked={!useDefault} />
<input type="text" onKeyUp={() => setUseDefault(false)} />
</div>
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
I am working on a form in which I have a section of it that needs to have at least one of the checkboxes checked. I am using ReactJS and a React Hook Form.
Here is the checkbox section of code within my render function:
{/* Checkbox group. User must select at least one medium. */}
<label><b>Medium (check all that apply): *</b></label>
<div>
<label>
<input type="checkbox" name="medium" value="Design & Illustration" onChange="validateMedium();"/><span>Design & Illustration</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Digital Art" onChange="validateMedium();"/><span>Digital Art</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Drawing" onChange="validateMedium();"/><span>Drawing</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Painting & Mixed Media" onChange="validateMedium();"/><span>Painting & Mixed Media</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Photography" onChange="validateMedium();"/><span>Photography</span>
</label>
</div>
Here is the function I am trying to write to validate the checkbox group:
function validateMedium() {
var mediumCheckboxes = document.getElementsByName("medium");
var okay = false;
for (var i = 0, len = mediumCheckboxes.length; i < len; i++) {
if (mediumCheckboxes[i].checked) {
okay = true;
break;
}
}
if (okay) {
alert("Thank you");
} else {
alert("Please check at least one medium.");
}
}
How do I integrate the validation function I've written specifically for the checkbox group on this form? If the user does not check at least one checkbox when the submit button is clicked, I would like the error to appear. I do not want to use jQuery.
Each of your inputs should have a ref prop which would register the validation function:
ref={register({
required: false,
validate: validateMedium })}
I found many checkbox related questions but not was related like mine. Please check and help.
I have 10+ checkboxs which are dynamically creating as per the API data (looping list).
Here I want to know onClick whether the checkbox is unchecked or checked (accordingly i'll call different API).
To know/tack the checked or unchecked, i tried using the state. But the problem is while i'm checking/ unchecking all checkboxs are affecting with same.
Please help me handle that individually.
My code as follows:
this.state = {
isChecked: true,
};
handleClick = (e) => {
console.log("clicked", e.fieldId);
this.setState((prevState) => ({
isChecked: !prevState.isChecked,
}));
if(this.state.isChecked){
// update to API 1
}else{
// update to API 2
}
};
<input
type="checkbox"
checked={this.state.isChecked}
onClick={() => this.handleClick(subitems)}
name="check"
/>
<label className="form-check-label cost-blue">
{subitems.message}
</label>
Note: some checkboxs are already checked as per API list data. But by using the state, i unable to handle that also
Edit: This how i'm looping from API
Object.keys(dataMap).map((value, key) => {
return (
<div className="mt-10">
<div className="row text-center m-0 p-box white">
<div>
<img src={plant_icon} alt="plant" />
<span className="mb-0"> {value}</span>
</div>
</div>
{dataMap[value].map((subitems) => {
return (
<div className="form-check custom-cb m-10">
<input
className="form-check-input mt-7"
type="checkbox"
checked={this.state.isChecked}
onClick={() => this.handleClick(subitems)}
name="check"
/>
<label className="form-check-label cost-blue">
{subitems.message}
</label>
</div>
);
})}
</div>
);
})
I have component that renders jsx like this
<section>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
<div>
<input type="text" class="hide" />
<button id={item.uniqueID}>show input</button>
</div>
</section>
I want this behavior, when I click the button in the first div, the input in the first div will show. Similarly, I click the button in the third div the input in third div will show.
How you do that in react?
If it were me I would make a new component out of:
show input
Lets call it <InputToggler/>
and then it would have a state of inputHidden for its own input and use classes to determine if it should show or not and the button would have an onclick handler to toggle the state of hidden or shown. Here is a pen showing exactly that
http://codepen.io/finalfreq/pen/VKPXoN
class InputToggler extends React.Component {
constructor() {
super();
this.state = {
inputHidden: true
}
}
toggleInput = () => {
this.setState({
inputHidden: !this.state.inputHidden
})
};
render() {
const inputClass = this.state.inputHidden ? 'hide' : '';
const buttonLabel = this.state.inputHidden ? 'show input' : 'hide input'
return (
<span>
<input type="text" className={inputClass} />
<button onClick={this.toggleInput} id={this.props.item.uniqueID}>
{buttonLabel}
</button>
</span>
)
}
}
This is the concept not the exact code.
Each button should have onClick with callback to a function ex. toggleShow
<button id={item.uniqueID} onClick={this.toggleShow.bind(this)}>show input</button>
toggleShow do something like:
toggleShow(e){
var item = e.target.id;
this.setState({inputClassName1: "hide"})
at the same time the input field classname should refer to the state
Note that I omitted the fact that you have multiple objects, you may want to handle their references in arrays.