On selecting first dropdown then the second dropdown should show corresponding phonenumber in second dropdownlist and vice versa .how can we achieve it?
Code
import Select from "react-select";
const data = [
{ value: 1, label: "max", phone: "123" },
{ value: 2, label: "sam", phone: "345" },
{ value: 3, label: "denis", phone: "4444" }
];
export default function App(props) {
const [select1, setSelect1] = useState([]);
const [select2, setSelect2] = useState([]);
const filter1=data.filter((x)=>{return x.value===select2.value})
const filter2=data.filter((x)=>{return x.value===select1.value})
return (
<div className="App">
<Select
options={data}
value={select1}
onChange={(e) => {
console.log(e);
setSelect1(e);
setSelect2(e.phone);
}}
/>
<Select
options={data}
value={select2}
onChange={(e) => {
setSelect2(e);
setSelect1(e.value);
}}
/>
</div>
);
}
Related
I want to create a react form with dynamic inputs, those inputs are fetched from server.
I fetched the data and I have displayed the form but the problem was how to get the values of the inputs with the onChange method
Use a Usestate hook and assign the value fetched from the API there
eg:-
const [value,setValue] = useState(fetch());
function fetch(){
//API call...
//return the value got from the API
}
Now in form input field you can use this as value and have an onChange and change the value state.
eg:-
<input value={value.name} name="name" onChange={(e)=>handlechange(e)} />
in handlechange :
const handlechange = (e)=>{
const {name,value} = e.target;
setValue({...value,[name]:value});
};
After this you can have an useEffect, which will POST the value to the backend using another API for every changes made in the form
Here is the code sandbox link:https://codesandbox.io/s/blazing-moon-wxp4w7?file=/src/App.js
after some researches on stackoverflow here is my solution:
const [fields, setFields] = useState([{field:"", value:""}]);
useEffect(()=>{
if(fetchedData){
setFields(fetchedData.map((item)=>{
var rObj ={field:"", value:""};
rObj["field"] = item;
return rObj;
}));
}
},[fetchedData])
const handleChange = ( index, event ) => {
if(fields) {
let data = [...fields];
data[index]["value"] = event.target.value;
setFields(data);
}
}
/////////////////////////////////////////
{fetchedData.map((field, index) => (
<div key={index}>
<input
required
type="text"
name={field}
value={fields.field}
placeholder= {field}
onChange={event=>{handleChange(index, event)}}
/>
</div>
))}
Here is a sample code:
const GenerateForm() => {
const [formInputs, setFormInputs] = useState({});
const handleInputChange = event => {
const { name, value } = event.target;
setFormInputs({ ...formInputs, [name]: value });
};
return (
<form>
{formData.map(input => {
if (input.type === "text" || input.type === "number") {
return (
<div key={input.name}>
<label htmlFor={input.name}>{input.label}:</label>
<input
type={input.type}
name={input.name}
value={formInputs[input.name] || ""}
onChange={handleInputChange}
/>
</div>
);
} else if (input.type === "select" || input.type === "radio") {
return (
<div key={input.name}>
<label>{input.label}:</label>
{input.options.map(option => (
<div key={option.value}>
<input
type={input.type}
name={input.name}
value={option.value}
checked={formInputs[input.name] === option.value}
onChange={handleInputChange}
/>
{option.label}
</div>
))}
</div>
);
}
return null;
})}
</form>
);
}
const formData = [
{
name: "firstName",
label: "First Name",
type: "text"
},
{
name: "lastName",
label: "Last Name",
type: "text"
},
{
name: "age",
label: "Age",
type: "number"
},
{
name: "gender",
label: "Gender",
type: "radio",
options: [
{
value: "male",
label: "Male"
},
{
value: "female",
label: "Female"
}
]
},
{
name: "country",
label: "Country",
type: "select",
options: [
{
value: "india",
label: "India"
},
{
value: "usa",
label: "USA"
}
]
}
];
i'm building a checkbox todo List that checked checkbox is disappearing.
I have two problems.
checked checkbox remains after re-rendering
When the two checkboxes are left, they dont disappear.
Here is my codeSandBox:-----
I think this might be a setState issue, setItems([...items.filter((item) => !checkedItems[item.id])]); -> rerendering (this scope havecheckedItems ={false,true,false,false,false}) so, checkbox is remaining?
import "./styles.css";
import React from "react";
const todos = [
{ id: 0, value: "Wash the dishes" },
{ id: 1, value: "have lunch" },
{ id: 2, value: "listen to music" },
{ id: 3, value: "running" },
{ id: 4, value: "work out" }
];
export default function App() {
const [items, setItems] = React.useState(todos);
const [checkedItems, setCheckedItems] = React.useState(
new Array(todos.length).fill(false)
);
const checkHandler = (idx) => {
checkedItems[idx] = !checkedItems[idx];
setItems([...items.filter((item) => !checkedItems[item.id])]);
setCheckedItems([...checkedItems]);
};
return (
<div className="App">
{items.map((todo, idx) => (
<div key={idx}>
<span>{todo.value}</span>
<input
type="checkbox"
checked={checkedItems[idx]}
onChange={() => checkHandler(idx)}
></input>
</div>
))}
</div>
);
}
It is not good practice to use index as key when iterating objects.
Since you have id, use this.
{items.map(todo => (
<div key={todo.id}>
<span>{todo.value}</span>
<input
type="checkbox"
checked={checkedItems[todo.id]}
onChange={() => checkHandler(todo.id)}
></input>
</div>
))}
You mess with indexes and the result is confusing.
If you want the items to be persisted and shown, just remove this line
setItems([...items.filter((item) => !checkedItems[item.id])]);
Demo
You do not need to have a separate checkedItems state. You can add a field checked in your todo object.
const todos = [
{ id: 0, value: "Wash the dishes", checked: false },
{ id: 1, value: "have lunch", checked: false },
{ id: 2, value: "listen to music", checked: false },
{ id: 3, value: "running", checked: false },
{ id: 4, value: "work out", checked: false }
];
export default function App() {
const [items, setItems] = React.useState(todos);
const checkHandler = (idx) => {
setItems(items.filter((item) => item.id !== idx));
};
return (
<div className="App">
{items.map((todo, idx) => (
<div key={idx}>
<span>{todo.value}</span>
<input
type="checkbox"
checked={todo.checked}
onChange={() => checkHandler(todo.id)}
></input>
</div>
))}
</div>
);
}
The key mistake you're making here is in onChange={() => checkHandler(idx)} and then using idx as your variable to filter out your items. idx does NOT equal the ids you have in your todo list, it will change based on the number of items left in the array.
The filter can also be improved to just be
setItems([...items.filter((item) => item.id !== idx)]);
The final code should look something like this (I'm not sure what checkedItems is meant to be doing or what it's for so it's not a consideration in this answer).
import "./styles.css";
import React from "react";
const todos = [
{ id: 0, value: "Wash the dishes" },
{ id: 1, value: "have lunch" },
{ id: 2, value: "listen to music" },
{ id: 3, value: "running" },
{ id: 4, value: "work out" }
];
export default function App() {
const [items, setItems] = React.useState(todos);
const [checkedItems, setCheckedItems] = React.useState(
new Array(todos.length).fill(false)
);
const checkHandler = (idx) => {
checkedItems[idx] = !checkedItems[idx];
setItems([...items.filter((item) => item.id !== idx)]);
setCheckedItems([...checkedItems]);
};
return (
<div className="App">
{items.map((todo, idx) => (
<div key={idx}>
<span>{todo.value}</span>
<input
type="checkbox"
onChange={() => checkHandler(todo.id)}
></input>
</div>
))}
</div>
);
}
Simply remove this line:
setItems([...items.filter((item) => !checkedItems[item.id])]);
that causes the list items to be filtered.
I'm trying to update a State in my project based on a User Selection from a dropdown menu.
I passed the 2 states (roomType & occupants) along with their setter/change functions (onRoomTypeChange & onOccupantsChange) from the parent Component.
I’ve tried to read through the React Select Library, but having trouble.
Wondering if someone could point me in the right direction.
import React from 'react';
import Select from 'react-select';
const roomOptions = [
{ value: 'Standard', label: 'Standard' },
{ value: 'Delux', label: 'Delux' }
];
const occupantOptions = [
{ value: 1, label: '1' },
{ value: 2, label: '2' },
{ value: 3, label: '3' },
{ value: 4, label: '4' },
];
const RoomDetails = (props) => {
let {
roomType,
onRoomTypeChange,
occupants,
onOccupantsChange
} = props;
const handleChange = (e) => {
onRoomTypeChange(e.target.value);
};
return (
<div>
<div className="form-group">
<label className="select-label">Room Type: {roomType} </label>
<Select
// value={e.target.value}
onChange={handleChange}
options={roomOptions}
theme={theme}
/>
<label className="select-label">Guests: {occupants}</label>
<Select
value={occupants}
onDatachange={onOccupantsChange}
options={occupantOptions}
theme={theme}
/>
</div >
</div>
);
};
export default RoomDetails;
I resolved the and wanted to post an update:
I had installed another package called “react-dropdown-select” that I removed from my package.json, I believe was interfering with my react-select package .
The return object was not an event, it was the selected object from the corresponding options array. I destructured the value property in the parameter and used the Setter Function on the value only.
I originally included a Value= attribute on the Select Component, which was set to my current state value
<Select
value={stateProperty}
/>
When I removed the Value attribute, the bug was gone
(Here is the solution)
import React from 'react';
import Select from 'react-select';
const roomOptions = [
{ value: 'Standard', label: 'Standard' },
{ value: 'Delux', label: 'Delux' }
];
const occupantOptions = [
{ value: 1, label: '1' },
{ value: 2, label: '2' },
{ value: 3, label: '3' },
{ value: 4, label: '4' },
];
const RoomDetails = (props) => {
let {
onRoomTypeChange,
onOccupantsChange
} = props;
const handleChangeRoom = ({ value }) => {
console.log(value);
onRoomTypeChange(value);
};
const handleChangeOccupants = ({ value }) => {
console.log(value);
onOccupantsChange(value);
};
return (
<div>
<div className="form-group mb-2">
<span className="form-label mt-3">Room Type </span>
<Select
onChange={handleChangeRoom}
options={roomOptions}
theme={theme}
placeholder="Room Type"
/>
<span className="form-label mt-3">Guests</span>
<Select
onChange={handleChangeOccupants}
options={occupantOptions}
theme={theme}
placeholder="Number of Guests"
/>
</div >
</div>
);
};
export default RoomDetails;
The form data is set by an the data object. Need help figuring out how to update /handleChange the text inputs
I've tried unique name, those probably won't work because it wont match the "key" in the object.
Any help / input is appreciated!
Data:
export default
{
name: "Restaurants Name",
menu: [
{
category: "Appetizers",
items:
[ {
imgurl: "https://source.unsplash.com/400x200/?863127",
title: "Food 2",
desc: "",
price: "500"
},
{
imgurl: "",
title: "Food 1",
desc: "",
price: "300"
}
]
},
{
category: "Entree",
items:
[ {
imgurl: "https://source.unsplash.com/400x200/?863127",
title: "Entree 1",
desc: "",
price: "500"
},
{
imgurl: "",
title: "Entree 1",
desc: "",
price: "300"
}
]
},
]
}
Code:
import React, { useEffect, useState } from "react";
import "./../App.css"
import MenuData from "../data"
function Edit() {
const [formState, setFormState] = useState(MenuData);
useEffect(() => {
console.log(formState)
}, []);
const handleNameChange = (event) => {
const name = event.target.name;
// console.log(name)
setFormState(prevState => ({
formState: { // object that we want to update
...prevState.formState, // keep all other key-value pairs
[name]: event.target.value, // update the value of specific key
menu: {
...prevState.menu,
items: {
...prevState.menu.items
}
}
}
}))
// setFormState({
// ...formState,
// [name]: event.target.value,
// })
};
const handleChange = (categoryIndex, event) => {
// const values = [...formState]
// values[categoryIndex][event.target.name] = event.target.value;
// setFormState(values);
const name = event.target.name;
// setFormState(prevState => ({
// formState: {
// ...prevState.formState,
// menu: {
// ...prevState.menu,
// items{
// ...prevState.items
// }
// }
// }
// }));
};
return (
<div className="App">
<div>
<input name="nameField" id="nameField" maxLength="300" value={formState.name} onChange={handleNameChange} /> <br />
{formState.menu && formState.menu.map((menuitem, categoryIndex) => {
return (
<div key={categoryIndex}>
<div class="line"></div>
<h2>{menuitem.category}</h2>
<input name={"category-" + categoryIndex} id="CategoryField" maxLength="40" categoryIndex={categoryIndex} onChange={event => handleChange(categoryIndex, event)} value={menuitem.category} />
{
menuitem.items.map((item, index) => {
return(
<div key={index}>
<input name={"title-" + index + categoryIndex} id="titleField" maxLength="40" categoryIndex={categoryIndex} onChange={handleChange} value={item.title} /> <br />
<input name="desc" id="descField" maxLength="200" categoryIndex={categoryIndex} onChange={handleChange} value={item.desc} />
<br /><br />
</div>
)
})
}
</div>
)
}
)
}
</div>
</div>
);
}
export default Edit;
UPDATED
Not able to figure out the onChange function to updated nested items
Currently, I started learning to react in the Udemy course "react-for-the-rest-of-us".
now, I'm trying to approach the state hook from the child component, and I get the above error.
my target is to add another element to the state by getting it's values from the user input
this is the parent component:
import React, { useState } from "react";
import AddPetForm from "./FormPet";
function Header(props) {
const [pets, setPets] = useState([
{ name: "Meowsalot", species: "cat", age: "5", id: 123456789 },
{ name: "Barksalot", species: "dog", age: "3", id: 987654321 },
{ name: "Fluffy", species: "rabbit", age: "2", id: 123123123 },
{ name: "Purrsloud", species: "cat", age: "1", id: 456456456 },
{ name: "Paws", species: "dog", age: "6", id: 789789789 },
]);
const pet = pets.map((pet) => (
<Pet name={pet.name} species={pet.species} age={pet.age} id={pet.id} />
));
return (
<div>
<LikedArea />
<TimeArea />
<ul>{pet}</ul>
<AddPetForm set={setPets} />
</div>
);
}
function Pet(props) {
return (
<li>
{props.name}is a {props.species} and is {props.age} years old
</li>
);
}
and this is the child component:
import React, { useState } from "react";
function AddPetForm(props) {
const [name, setName] = useState();
const [species, setSpecies] = useState();
const [age, setAge] = useState();
console.log(props.set);
function handleSubmit(e) {
e.preventDefault();
props.set((prev) => {
prev.concat({ name: name, species: species, age: age, id: Date.now() });
setName("");
setSpecies("");
setAge("");
});
}
return (
<form onSubmit={handleSubmit}>
<fieldset>
<legend>Add New Pet</legend>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
/>
<input
value={species}
onChange={(e) => setSpecies(e.target.value)}
placeholder="species"
/>
<input
value={age}
onChange={(e) => setAge(e.target.value)}
placeholder="age in years"
/>
<button className="add-pet">Add Pet</button>
</fieldset>
</form>
);
}
export default AddPetForm;
You aren't returning the new concatenated array. So when you call props.set it should be this:
props.set((prev) => {
setName("");
setSpecies("");
setAge("");
return prev.concat({ name: name, species: species, age: age, id: Date.now() });
});
If you don't return anything, then technically the return value is undefined, so that's what it sets the state to. Then you get the error when you try to .map it