Add input on click ReactJS - javascript

I have a problem, when I click on a button to add a new line of multiple input, the data is noted in all the inputs! can you help me please I have been on this problem for several days and I cannot solve it, thanks
{inputs.map((inputValue, index) => <>
<Number key={"addQ" + index}
type="input"
placeholder="3"
name="quantiteTab[]"
label="Quantité*"
classField="col-lg-2"
onChange={(value) => setInputs(inputs => {
let copy = [...inputs];
copy[index] = value.target.value;
return copy;
})}
value={inputValue}/>
<Number key={"addP" + index}
type="input"
placeholder="206"
name="poidsTab[]"
label="Poids total (kg)"
classField="col-lg-3"
onChange={(value) => setInputs(inputs => {
let copy = [...inputs];
copy[index] = value.target.value;
return copy;
})}
value={inputValue}/>
<button className="button add-line" type="button" onClick={() => setInputs(inp => [...inp,''])}>Add</button>

<Number key={"addQ" + index} - the key should not be dependent on an array index. Randomly generate a key or pass something constant but unique from inputValue.

Related

React .map() won't update when .filter changes

I have a page with a search, you can filter the results with a range slider. I have an onChange event on the slider that should dynamically set a .filter param. I am passing that param to a chained .sort().filter(props.filter).map().
When I use the slider, it is changing the parameter that I'm passing through, but the .map() is not updating the results.
Any help greatly appreciated:
let genderSpecificFilter = 'All';
let rangeSpecificFilter = 'All'
let sendFilteredDoctors = () => filterDoctors(genderSpecificFilter,rangeSpecificFilter);
function changeRangeFilterParams() {
rangeSpecificFilter = checkBoxDistanceMap[document.getElementById('range-miles').value];
sendFilteredDoctors = filterDoctors(genderSpecificFilter,rangeSpecificFilter);
console.log(rangeSpecificFilter)
}
<PrintSearchResults
doctors={doctors}
filters={sendFilteredDoctors}
/>
import PrintDoctor from "./printdoctor";
function PrintSearchResults(props) {
return (
<div>
{props.filters}
<p className="text-xl text-gray-350">
Total Results:
<span className="ml-3" id="total-results-num">
{props.doctors.results
.sort((a, b) => a.locations[0].distance - b.locations[0].distance)
.filter(props.filters).length}
</span>
</p>
{props.doctors.results
.sort((a, b) => a.locations[0].distance - b.locations[0].distance)
.filter(props.filters)
.map((doctor, key) => (
<PrintDoctor
image={doctor.image}
url={doctor.url}
fullName={doctor.fullName}
specialties={doctor.specialties}
locations={doctor.locations}
gender={doctor.gender}
key={key}
/>
))}
</div>
);
}
export default PrintSearchResults
Edit:
On change coming from here:
<input onChange={changeRangeFilterParams} type="range" min="1" max="6" className="slider" defaultValue="6" id="range-miles" />

How to get the value of a radio input which is by default checked?

I have a radio button inside a .map method and the first is checked defaultChecked={index === 0}, how do I get the value of the option here? without using plain javascript
const [optionData, setOptionData] = useState({})

{variant.options.map((option, index) => {


<input
type="radio"
name="variant-select"
id="variant-select"
className="focus:ring-0 focus:ring-offset-0 focus:text-red-600 text-red-600 border-none -mt-1 cursor-pointer z-10"
defaultChecked={index === 0}
value={index}
onClick={(e) => {
setOptionData(option)
 }
}}
/>
}
}
This syntax may help you:function myFunction() { var x = document.getElementById("myRadio").value; document.getElementById("demo").innerHTML = x; }

Render number of elements based on users input

I am trying to render multiple Input elements based on number that user enters. I store the value in my count constant that dynamically changes. Then in my returnForm function I am trying to return the elements using for loop, but with no luck.
const returnForm = () =>
{
let items = [];
for (var i = 0; i < count; i++)
{
items.push(
<div key={i}>
<TextInput source="name" validate={required()} />
<br></br>
<ArrayInput source="tags" label="resources.vid.fields.tags" style={{ width: '40%' }}>
<SimpleFormIterator>
<TagsEdit addLabel={true} label="resources.vid.fields.tag" />
</SimpleFormIterator>
</ArrayInput>
<br></br>
<TagsList addLabel={true} label="resources.vid.fields.tagsList" />
</div>
);
return items;
}
}
Elements are only rendered one time even though value of count is different. Any ideas what am I doing wrong?
Thank you in advance.
try to move return out of loop

react hooks: input onChange first character can not be deleted

I got some inputs to create/update a formular,
1) if value={question}, everything works except that I can not delete the last character (= first character of the input)
2) if I dont mention value, it's all good except when I want to change questions orders with Chevron icon button, database is well changed but input value is still displayed at the last place.
<input
type="text"
value={question}
placeholder="blabla"
onChange={event => {
event.preventDefault();
const value = event.target.value;
setUpdatedQuestion(value);
}}
/>
I tried to add if (event.target.value == "" || event.target.value) to onChange but does not work either
OK I found something, but it is a McGyver tip, not very clean : adding one space before all new add question ahah. But then I can't see my placeholder anymore :/
FYI : question is coming from a questions.map, setUpdatedQuestion do update questions, newOrder also do update questions
//in QuestionsContent.js (questions is a questions tab)
const QuestionsContent = props => {
return (
<form onSubmit={onSubmit}>
{isLoading === false && questions.length > 0
? questions.map((question, i) => {
return (
<div key={i}>
<QuestionLine
{...question}
questions={questions}
setQuestions={setQuestions}
setNewOrder={setNewOrder}
/>
</div>
);
})
: null}
<button
onClick={event => {
event.preventDefault();
setAddQuestion({
question: null,
type: "texte"
});
}}
>
Add a question
</button>
</form>
);
};
//in QuestionLine.js:
const QuestionLine = ({
question,
setNewOrder,
setQuestions,
questions
}) => {
const [updatedQuestion, setUpdatedQuestion] = useState("");
// * UPDATE QUESTION *******************************
useEffect(() => {
if (updatedQuestion !== "") {
const tab = [];
for (let j = 0; j < questions.length; j++) {
if (j === i) {
const newObject = {
question: updatedQuestion,
type: type
};
console.log("adding updatedQuestion ===>", newObject);
tab.push(newObject);
} else {
tab.push(questions[j]);
}
}
setQuestions(tab);
setUpdatedQuestion("");
}
}, [updatedQuestion]);
return (
<div >
{/* QUESTION */}
<input
type="text"
value={question}
placeholder="blabla"
onChange={event => {
event.preventDefault();
const value = event.target.value;
setUpdatedQuestion(value);
}}
/>
</div>
);
};
thanks for your precious help
The problem probably comes from the condition in the useEffect : when you want to delete the last character of the string, the state of updatedQuestion is empty and therefore the condition is not executed

How to display array values in dropdownlist using react js?

I want to display all months in dropdown using react js. Below is my code .I have used moments to fetch all 12 months. I am getting value in console but not in my dropdown.
To display the dropdown values want to use the .
I have used that also. I don't know where I went wrong. Could any one can help me with this? Thanks in advance.
const fareMon = () => {
const months = [];
const monthList = moment.months();
months.push(<option value={monthList} />);
console.log('MONTHS123', monthList);
return months;
};
return (
<div className={styles.formClm2}>
<Form.Group className={styles.formGroup}>
<Form.Label>{t('PaymentPage.lblExpiry')}</Form.Label>
<div className="double">
<Form.Control required as="select" name="startDate">
<option value="">Months</option>
{fareMon()}
</Form.Control>
</div>
</Form.Group>
</div> )
const fareMon = () => {
const monthList = moment.months();
const months = monthList.map(item => (
<option key={item} value={item}>{item}</option>
));
console.log('MONTHS123', monthList);
return months;
};
you need to iterate the monthsList and map each month to a <option>.
You need to iterate over the array of months and set the value in the form controls options element.
Something like this, something simplified.
<Form.Control required as="select" name="startDate">
{months.map(month => (<option key={month.id} value={month.value}>{month.label}</option>))}
</Form.Control>
Key points:
Iterate over a data source of some description.
Ensure each option has a key prop
moment.months() returns an array containing the months name, you don't need to create a new array.
You have to map over the array inside the Select to show up the options.
Example:
const fareMon = () => {
const monthList = moment.months();
return monthList;
};
return (
<div className={styles.formClm2}>
<Form.Group className={styles.formGroup}>
<Form.Label>{t('PaymentPage.lblExpiry')}</Form.Label>
<div className="double">
<Form.Control required as="select" name="startDate">
<option value="">Months</option>
{fareMon().map( month => (<option key={month} value={month}>{month}</option>))}
</Form.Control>
</div>
</Form.Group>
</div>
)

Categories

Resources