I am trying to get the checked values of a checkbox and then display them in a field. I have two files the index which has the input field and then the checkbox is made in a modal which is a different component, the selectlanguage. I want that when a user checks one or more checkbox(es), the value(s) appears on the input and when unchecked, the value leaves the field.
Presently, what I am able to achieve is only a single value appearing on the input field.
Here is a snippet of the code.
index.js
import React, { useState } from "react";
import SelectLanguage from "../../components/modal/selectLanguage";
const index = () => {
const [chosenLanguage, setChosenLanguage] = useState([]);
function checkLanguage(e) {
setChosenLanguage(e.target.name);
};
<label className="relative block p-3 border-b-2 border-gray-200 w-full" for="languages">
<span for="languages">languages</span>
<input
id="languages"
type="text"
placeholder="Spanish, Arabic"
autoComplete="off"
onClick={languageShowModal}
value={chosenLanguage}
/>
</label>
}
export default index;
selectlanguage.js
import { useState } from "react";
export default function SelectLanguage({ open, handleClose, checkLanguage }) {
const handleCheckbox = (e) => {
alert(e.target.name);
};
return open ? (
<div>
<label>
<input type="checkbox" name="spanish" onChange={checkLanguage} />
<span>spanish</span>
</label>
<label>
<input type="checkbox" name="spanish" onChange={checkLanguage} />
<span>french</span>
</label>
<label>
<input type="checkbox" name="spanish" onChange={checkLanguage} />
<span>arabic</span>
</label>
</div>
) : (
""
);
}
It isn't exactly clear to me how you have things hooked up, but a good strategy is to reflect the state of the DOM into your React state (Controlled Components), and then have a way of displaying that state. In your case, you want to store the state of a bunch of checkboxes, and one way to do this is with a map.
export const MyComponent = () => {
const [ chosenLanguages, setChosenLanguages ] = useState({})
const checkLanguage = (e) => {
setChosenLanguages(prev => ({
...prev,
[e.target.value]: e.target.checked,
}))
}
const showLanguages = () => {
return Object.entries(chosenLanguages)
.filter(([_, checked]) => checked)
.map(([name, _]) => name)
.join(', ')
}
return (
<input value={showLanguages()} />
)
}
Instead of an array, chosenLanguages is a map of language names to their checked state, for example:
{
arabic: true,
spanish: false,
french: true,
}
When you've stored your state like this, you can transform it in whatever way you want when you render.