How to display array values in dropdownlist using react js? - javascript

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>
)

Related

how to create an array of arrays in react?

I'm trying to code a wordle clone using React, but the twist is that the player can choose the number of attempts and the length of the word. And i want to rendre the box depending on these two parameter so i used the following line :
var grid = Array(this.props.nbrAttempts).fill(0).map(row => new Array(this.props.wordLenght).fill(' '))
the first time the component render i get a 4*4 array, but after changing the parameter i get always a 1*1, and i can't figure what's the problem.
the Box component:
function App() {
const [boxParam, setBoxParam] = useState({nbrAttempts: 4, wordLenght : 4,});
let renderBox = ()=>{
setBoxParam({
nbrAttempts: document.getElementById('nbAttempts').value,
wordLenght : document.getElementById('wordLength').value,
})
}
return (
<div className="App">
{/* add input field with number of attempts as label */}
<label htmlFor="nbAttempts">Attempts</label>
<input type="number" id="nbAttempts"/>
<label htmlFor="nbAttempts">Word length</label>
<input type="number" id="wordLength"/>
<button onClick={()=>renderBox()}>OK</button>
<Box nbrAttempts={boxParam.nbrAttempts} wordLenght={boxParam.wordLenght} />
</div>
);
}
I just replaced
var grid = Array(this.props.nbrAttempts).fill(0).map(row => new Array(this.props.wordLenght).fill(' '))
with
let grid = [];
for (let i = 0; i < this.props.nbrAttempts; i++) {
grid.push(new Array(this.props.wordLenght).fill('_'));
}
and everything just worked fine

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" />

Add input on click ReactJS

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.

Store values from multiple select in react

I have a variable with the number of select items, this number depends on some API, and I want to store the selection of each question into localstorage so each time the page reloads the selection stays remained, I don't know how to do it.
{ Object.entries(this.state.liste).map( ([ke,values]) => {
let question=ke
return (
<div name = "question" >
<h6 className="left">{ke}</h6>
< select className="right" key={values} name = "answer to each question" onChange={(event) =>
this.handleChangeaa(question,event)} >
<option value={this.state.selected} selected disabled hidden onChange={(value)=>
console.log(value)}> Not answered </option>
{Object.values(values).map(key=>{
return (<option key={key.id} id={key}>{key}</option>) })}
</select>
</div>
) })}
In localStorage, you can only set a value as a string. You simply have to insert in the localStorage some pairs of key/values for each questions that have a selected option. In this case, the key will be the id of your question and the value the value of your selected option.
In your handleChangeaa callBack, you will have something like this :
handleChangeaa(question, event) {
// Check before if the localStorage is available
localStorage.setItem(question.id, event.target.value);
}
Then when your form component will be instantiated, you will simply have to retrieve this information from your localeStorage with the localStorage.getItem function :
componentDidMount() {
// Check if localStorage is available
const stateListCpy = {...this.state.liste}
["question1", "question2"].forEach((questionId) => {
const questionValue = localStorage.getItem(questionId);
if (questionValue) {
const questionIndex = stateListCpy.findIndex((questionBlock) => questionBlock.ke === questionId )
if (questionIndex !== -1) {
stateListCpy[questionIndex].values = questionValue;
}
}
})
this.setState({
liste = stateListCpy;
})
}
And with that you will have your selects initialized with the right values from your localStorage.
Good luck !

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

Categories

Resources