Adding images to radio buttons using jsx (react & next js)
Hello again, in this post am going to be sharing with you a way to add images to radio button using jsx(react js & next js)
Alright, to start with create a simple index.js page and within it setup a simple functional component like so
function RadioButtons() {
const submitHandler = (e) => {
e.preventDefault();
var formData = new FormData(e.target);
const form_values = Object.fromEntries(formData);
console.log("qq", form_values);
};
return (
<>
<div className="container p-3">
<h5 >Select Favourite Framework</h5>
<form onSubmit={submitHandler}>
<div>
<input
type="radio"
name="radio-image"
id="radio-form-image1"
defaultValue={"react"}
/>
<label htmlFor="radio-form-image1">
<img
alt="radio-image-select-1"
layout="responsive"
width={"40px"}
height={"40px"}
src={"/logo192.png"}
/>
</label>
</div>
<br />
<div>
<input
type="radio"
name="radio-image"
id="Radioform-image2"
defaultValue={"django"}
/>
<label htmlFor="Radioform-image2">
<img
alt="image-select-2"
width={"30"}
height={"30"}
src={"/django.svg"}
/>
</label>
</div>
<br />
<input type={"submit"} />
</form>
</div>
</>
);
}
export default RadioButtons;
From the code above you can see that our page has a basic form within which there are two wrapper div's . Within each div there is an input tag with a corressponding label tag. All you have to do is instead of inputing a text as the value of the label tag you just add an image tag instead ("img") that links to a specific image you want for the radio button. You can change the default size of the image in "px" by changing the value in the width and height attributes as shown above.
Replacing the img tag with Next js Image component also works
Result
When you select an option and submit the form the result gets outputed out in the browser console due to the submitHandler we specified in our code.
Conclusion
Follow the steps above we have been able to add image radio buttons to a simple jsx form whose result gets outputed on the console onsubmit. As always thanks for reading if you have any questions or comments about the post then feel free to leave a comment down below and i'll reply you as soon as I can.