Hi i am trying to manage multiple checkbox with multiple input in same map can anyone tell me how can i do it here is my code the main problem is that when i try to add some input afterwards another ita takes wronge indexing
GetCryptoHtml = (criptoList) => {
return criptoList.map((value, i) => {
return (
<>
<div className="col-md-3 col-12">
<input
className="checked"
id={i + "checkbox"}
type="checkbox"
onChange={(e) => this.onChangeCheck(e, value, i)}
name={"cryptoCurrency" + [i]}
value={value.id}
/>{" "}
<label for="vehicle1"> {value.name}</label>
</div>
<div className="col-md-9 col-12">
<div className="form-group">
{/* {
checkingInput ? */}
<input
type="text"
id={i + "percentage"}
name={"percentage" + [i]}
onChange={(e) => this.onChangeInputBox(e, i ,value.name)}
value={this.state.percentage[i]}
className="form-control"
/>
{/* <input type="text" onChange={(e) => this.checkWordInput(e)} id="percentage[i]" name="percentage[i]" /> : <></> */}
{/* } */}
</div>
</div>
<br />
</>
);
});
And Here's the onChange function for both
onChangeCheck = async (e, value, i) => {
var percentage = document.getElementById(i + "percentage").value;
if (e.target.checked) {
this.setState({
checkedCheck: true
});
this.state.data2.push(value.short_name);
if (this.state.percentage[i] !== undefined) {
this.state.percentage[i] = this.state.percentage[i];
} else {
this.state.percentage.push("");
}
} else {
this.setState({
checkedCheck: false
});
this.state.data2.pop(value.short_name);
this.state.percentage[i] = "";
}
this.setState({
cryptoCurrency: "update"
});
Maybe the issue you are facing is because of the indexing process from where i can see the problem is the your index value on change is setting by default 0 and everytime you add your input it takes one input back to add value in current section. You can check the indexing and current id if they both are matched and after then enter the value using event
Related
I know this before but I forgot how did I do it..so basically let say I have
const [showItem,setShowItem] = useState({})
const [updateName,setUpdateName] = useState('')
and then I have a props function that will do something like this...this props is callable for array of items and I want to do this to make it more cleaner and reuseable.
<ItemsEdit items={showItem} setUpdateName_= { setUpdateName } updateName = { updateName } ></ItemsEdit>
Now as you see, when I'm trying to pass my setUpdateName_ and updatename.
UPDATE
This is the map for my items that will call the <ItemsEdit/> for specific id only in my buttons. (but this not affect anything in form)
{nfts.map((nft,i) => {
return(
<div
className="items"
key={nft.id}
>
{showItem.id == nft.id ? <>
<form onSubmit={handleSubmit}>
<ItemsEdit
items={showItem}
setUpdateName= { setUpdateName }
updateName = { updateName }
/>
</form>
</> : <>
<Items items={nft}></Items>
</>}
</div>
)
})}
and here is the <ItemsEdit/>
so for every key that I press it will lose the focus in input but when I used autoFocus = "autoFocus" in the input text it will works but the only thing is that it will the same text in other items..so its not the best idea for me.
const ItemsEdit = ({items,setUpdateName,updateName}) => {
return (
<>
<input
id='name'
type="text"
key="text"
// autoFocus="autoFocus"
value = {updateName}
placeholder="NFT name"
onChange={ e => setUpdateName( e.target.value )}
></input>
<p>{items.id}</p>
<img src={items.data.img} alt="" />
<div className="buttons">
<button
type='submit'>
Update
</button>
<button type='submit' className='left'
onClick={
() => {
setShowItem({})}
}>
<ion-icon name="arrow-back-circle-outline"></ion-icon>
</button>
</div>
</>
)
}
I now have an answer but this kinda nasty for me
so for the <ItemsEdit/> I would call it something like this
{ItemsEdit(
{items:showItem,
setUpdateName:setUpdateName,
updateName:updateName}
)}
and just remove the return of and change the { } into ( )just like this
const ItemsEdit = ({items,setUpdateName,updateName}) => (
)
I am having trouble handling cases where the users phone number comes in undefined. I attempted to make the state conditional which I believe is bad practice so now I am using the useEffect hook to update the state on page load but now my onChange function in the field is not working for updating the state. Here's my code:
const EditableSection = ({
profile,
patientSex,
editingProfile,
setEditingProfile,
userID,
setProfile,
}) => {
const [PCPAreaCode, setPCPAreaCode] = useState();
const [PCPThreeDigit, setPCPThreeDigit] = useState();
const [PCPFourDigit, setPCPFourDigit] = useState();
useEffect(()=> {
if (!profile.medicalProfile.primaryCareProvider.fax){
setPCPAreaCode("")
setPCPThreeDigit("")
setPCPFourDigit("")
}else{
setPCPAreaCode(profile.medicalProfile.primaryCareProvider.fax.split(" ")[0]);
setPCPThreeDigit(profile.medicalProfile.primaryCareProvider.fax.split(" ")[1].split("-")[0]);
setPCPFourDigit(profile.medicalProfile.primaryCareProvider.fax.split("-")[1]);
}
});
const submitData = async () => {
if (!validProps()) {
return;
}
let res = await api.UserRecords.update(userID, {
PCPhysician: {
fax: `${PCPAreaCode} ${PCPThreeDigit}-${PCPFourDigit}`,
name: PCPName
}
});
if (editingProfile) {
return (
<FormGroup>
<div className={styles.profileBlock}>
<div className="d-flex">
<Input
type="text"
maxLength="3"
defaultValue={PCPAreaCode.replace(/\(|\)/g, "")}
onChange={(e) => setPCPAreaCode(e.target.value)}
className={PCPFaxError ? styles.inputError : styles.inputField}
style={{ width: "4rem" }}
/>
<Input
type="text"
maxLength="3"
defaultValue={PCPThreeDigit}
onChange={(e) => setPCPThreeDigit(e.target.value)}
className={PCPFaxError ? styles.inputError : styles.inputField}
style={{ width: "4rem" }}
/>
<Input
type="text"
maxLength="4"
defaultValue={PCPFourDigit}
onChange={(e) => setPCPFourDigit(e.target.value)}
className={PCPFaxError ? styles.inputError : styles.inputField}
style={{ width: "4rem" }}
/>
</div>
</div>
</FormGroup>
)
}
return (
<>
<div className={styles.profileBlock}>
<h2>Primary Care Provider</h2>
<p>
{PCPName || "Not provided"}, Fax: {`${PCPAreaCode} ${PCPThreeDigit}-${PCPFourDigit}` || "Not provided"}
</p>
</div>
</>
So right now when I add a value in these input fields It doesnt update and im wondering if theres something im obviously doing wrong here?
Don't get this confused with checking each radio button I have on the page. I want to implement a check all button that sets the value of a nested object state equal to a certain value. I am storing each question in a nested state. Ex.
formQuestions({
kitchen: [question,question2,question3],
living: [question,question2,question3]
})
Four radio buttons are being made for each question. Now one radio button can only be selected at once. Each radio button has its' own value. Ex. `"Good", "Fair", "Poor", "N/A".
When a radio button is selected a state is generated dynamically for that section and question. Ex.
formAnswers({
kitchen: {
question: "Good"
question2: "Poor"
}
})
The goal here is the button that I want to create that checks only one value for each question Ex. clicks button question: "Good", question2: "Good" etc..
For me to set the state of a dynamic value I would need the "Section name" lets call it Name and the "Question" we'll call it question. That would give me access to the value like so formAnswers[Name][question]: value
I am trying to set that state from a component called SectionHeader. These contain the buttons.
SectionHeader.js
import { FormAnswersContext, FormQuestionsContext } from "../../Store";
function SectionHeader({ title, name }) {
const [formAnswers, setFormAnswers] = useContext(FormAnswersContext);
const [formQuestions, setFormQuestions] = useContext(FormQuestionsContext);
return (
<div>
<h1 className={styles["Header"]}>{title}</h1>
<div className={styles["MarkAllWrapper"]}>
<button className={styles["MarkAll"]}>
Mark all items as "Good" in this section
</button>
<br />
<button className={styles["MarkAll"]}>
Mark all items as "N/A" in this section
</button>
</div>
</div>
);
}
The parent of Section Header and the rest of the form code excluding the child radio buttons which I have explained, are in another component LivingRoom.js
LivingRoom.js
import { FormQuestionsContext, FormAnswersContext } from "../../Store";
function LivingRoomForm({ Name }) {
const [expanded, setExpanded] = useState(false);
const [formQuestions, setFormQuestions] = useContext(FormQuestionsContext);
const [formAnswers, setFormAnswers] = useContext(FormAnswersContext);
const array = formQuestions.living;
const onChange = (e, name) => {
const { value } = e.target;
setFormAnswers((state) => ({
...state,
[Name]: { ...state[Name], [name]: value },
}));
};
const handleOpen = () => {
setExpanded(!expanded);
};
return (
<div>
<Button
className={styles["CollapseBtn"]}
onClick={handleOpen}
style={{ marginBottom: "1rem", width: "100%" }}
>
<p>LIVING ROOM INSPECTION</p>
<FontAwesome
className="super-crazy-colors"
name="angle-up"
rotate={expanded ? null : 180}
size="lg"
style={{
marginTop: "5px",
textShadow: "0 1px 0 rgba(0, 0, 0, 0.1)",
}}
/>
</Button>
<Collapse className={styles["Collapse"]} isOpen={expanded}>
<Card>
<CardBody>
{array ? (
<div>
<SectionHeader title="Living Room Inspection" name={Name} />
<div
className={styles["LivingRoomFormWrapper"]}
id="living-room-form"
>
{array.map((question, index) => {
const selected =
formAnswers[Name] && formAnswers[Name][question]
? formAnswers[Name][question]
: "";
return (
<div className={styles["CheckboxWrapper"]} key={index}>
<h5>{question}</h5>
<Ratings
section={Name}
question={question}
onChange={onChange}
selected={selected}
/>
</div>
);
})}
</div>
<br />
<ImageUploader name="living" title={"Living Room"} />
</div>
) : (
<div></div>
)}
</CardBody>
</Card>
</Collapse>
</div>
);
}
If there is anything I am missing please let me know, I would be happy to share it. Cheers
Edit: for anyone that needs the radio buttons component.
Ratings.js
import React from "react";
import { FormGroup, CustomInput } from "reactstrap";
function Ratings({ selected, section, question, onChange }) {
return (
<div>
<FormGroup>
<div>
<CustomInput
checked={selected === "Good"}
onChange={(e) => onChange(e, question)}
type="radio"
id={`${section}_${question}_Good`}
value="Good"
label="Good"
/>
<CustomInput
checked={selected === "Fair"}
onChange={(e) => onChange(e, question)}
type="radio"
id={`${section}_${question}_Fair`}
value="Fair"
label="Fair"
/>
<CustomInput
checked={selected === "Poor"}
onChange={(e) => onChange(e, question)}
type="radio"
id={`${section}_${question}_Poor`}
value="Poor"
label="Poor"
/>
<CustomInput
checked={selected === "N/A"}
onChange={(e) => onChange(e, question)}
type="radio"
id={`${section}_${question}_NA`}
value="N/A"
label="N/A"
/>
</div>
</FormGroup>
</div>
);
}
I do not completely understand your question, I am sorry but I think this will help you.
Here is an implementation of radio buttons using react -
class App extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
handleChange = e => {
const { name, value } = e.target;
this.setState({
[name]: value
});
};
render() {
return (
<div className="radio-buttons">
Windows
<input
id="windows"
value="windows"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Mac
<input
id="mac"
value="mac"
name="platform"
type="radio"
onChange={this.handleChange}
/>
Linux
<input
id="linux"
value="linux"
name="platform"
type="radio"
onChange={this.handleChange}
/>
</div>
);
}
}
After a few attempts, I was able to figure out the solution to this issue.
The key here was to figure out a way to get gather each question so that it may be used as a key when setting the state. As my questions were stored in a ContextAPI, I was able to pull them out like so...
this may not be the best solution however it worked for me.
const setStateGood = () => {
formQuestions[name].map((question) => {
setFormAnswers((state) => ({
...state,
[name]: { ...state[name], [question]: "Good" },
}));
});
};
const setStateNA = () => {
formQuestions[name].map((question) => {
setFormAnswers((state) => ({
...state,
[name]: { ...state[name], [question]: "N/A" },
}));
});
};
I was able to map through each question since the name is being passed through props is a key inside the actual object, formQuestions[name]. Because i'm mapping through each one I can set that question as a key and return the new state for each question to whatever I would like.
However, if I was to create an onClick={setState('Good')}, React didn't like that and it created an infinite loop. I will look for more solutions and update this post if I find one.
I have a method in my React Component where based on a number value I display a row of components. The problem I am having is when I select on component the same value is selected in that component for a different row.
Here is my code
showSkillsModalCategoryUI = () => {
const {
startDate,
endDate,
errors,
reviewerSearch: {
contentAreaSkills,
otherSkills,
numOfDaysForReview,
numOfReviewerPositions,
},
} = this.state;
var data = [];
var length = numOfReviewerPositions; // user defined length
for (var i = 0; i < length; i++) {
data.push('undefined');
}
const row = data.map((position, index) => {
return (
<div key={index}>
<div className="ui grid">
<div className="three wide column">
<Form.Field
name="numOfDaysForReview"
label=""
placeholder="# of days"
value={numOfDaysForReview}
onChange={this.handleSearchFilterChange}
category={'numOfDaysForReview'}
control={AmsLookupDropdown}
fluid
search
selection
/>
</div>
<div className="four wide column">
<Form.Group>
<Form.Field
name="startDate"
control={DatePicker}
placeholder="Please select start Date"
isClearable={true}
selected={startDate && startDate}
selectsStart
minDate={moment()}
startDate={startDate && startDate}
onChange={this.handleStartDateChange}
/>
<Form.Field
name="endDate"
control={DatePicker}
placeholder="Please select end date"
isClearable={true}
selected={endDate && endDate}
selectsEnd
startDate={startDate && startDate}
minDate={startDate && startDate}
endDate={endDate}
onChange={this.handleEndDateChange}
/>
</Form.Group>
</div>
<div className="three wide column">
<Form.Field
name="languageSkills"
label=""
placeholder="Language"
defaultValue={'English'}
onChange={(e, { value }) =>
this.setState({
...this.state,
reviewerSearch: {
...this.state.reviewerSearch,
languageSkills: value,
},
})
}
category={'languages'}
control={AmsLookupDropdown}
fluid
multiple
search
selection
/>
</div>
<div className="three wide column">
<Form.Field
error={!!errors.contentAreaSkills}
name="contentAreaSkills"
label=""
placeholder="Content"
value={contentAreaSkills}
onChange={(e, { value }) =>
this.setState({
...this.state,
reviewerSearch: {
...this.state.reviewerSearch,
contentAreaSkills: value,
},
})
}
category={'contentAreaSkills'}
control={AmsLookupDropdown}
fluid
multiple
search
selection
/>
</div>
<div className="three wide column">
<Form.Field
name="otherSkills"
width={14}
label=""
placeholder="Other"
value={otherSkills}
onChange={(e, { value }) =>
this.setState({
...this.state,
reviewerSearch: {
...this.state.reviewerSearch,
otherSkills: value,
},
})
}
category={'otherSkills'}
control={AmsLookupDropdown}
fluid
multiple
search
selection
/>
</div>
</div>
</div>
);
});
return row;
};
For instance if I have 3 rows of these components and I select a language like english. All the language controls in each row will have english and if I try and change them on each row all change. So I cannot select an individual value.
All your rows use the same state, you need to create an array of states that takes the index of your map, so each row have an independent state, exemple:
onChange={(e, { value }) =>
this.setState({
...this.state,
['stateOfRow' + index]: theState ....
)
}
You get the idea, your rows doesn't have to share the same state if each one set its own.
To apply this to your case, the code will look like this:
The state:
const {
startDate,
endDate,
errors,
rowState // <== this is an Array []
} = this.state;
Portion if the code:
<Form.Field
name="otherSkills"
width={14}
label=""
placeholder="Other"
value={rowState[index].reviewerSearch.otherSkills}
onChange={(e, { value }) => {
this.setState(prevState => ({
rowState: [
...prevState,
[rowState[index]],
{
reviewerSearch: {
...prevState.rowState[index].reviewerSearch,
otherSkills: value,
},
},
],
}));
}}
category={"otherSkills"}
control={AmsLookupDropdown}
fluid
multiple
search
selection
/>
I want to retrieve the value of my checkbox when it is checked.
I am using this "http://react-component.github.io/checkbox/".
My code looks like this.
<div className="user_box">
{ check.map((values , i)=> {
return <Checkbox
name = "checkbox"
onChange={this.checkvalue.bind(this)}
value={values.username}
/>
})}
</div>
My function:
checkvalue(e){
// var all_users = [];
// var value = this.checkbox.value;
// all_users.push(value);
// console.log(all_users);
console.log('checkbox checked:', (e.target.checked));
}
I'm not understanding how to retrieve the value of the checkbox.
you need to pass the "e, Synthetic event parameter to your handler" :
handleChange(e) {
let isChecked = e.target.checked;
// do whatever you want with isChecked value
}
render() {
// ... your code here
return (
{/* your other jsx here */}
<Checkbox otherProps onChange={e => this.handleChange(e)} />
{/* your other jsx here */}
);
}
Use the Synthetic event parameter, here is an example:
const element1 = "boy";
const element2 = "girl";
<input
type="checkbox"
name={element1}
value={element1}
onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
</label>
<input
type="checkbox"
name={element2}
value={element2}
onChange={this.handleChange}
/>
<label for="element" style={{ fontSize: 35 }}>
{element2}
</label>
handleChange = (e) => {
// to find out if it's checked or not; returns true or false
const checked = e.target.checked;
// to get the checked value
const checkedValue = e.target.value;
// to get the checked name
const checkedName = e.target.name;
//then you can do with the value all you want to do with it.
};
Try this :
getChckeboxValue(event) {
const value = event.target.value;
}
In render:
<input onClick={this.getChckeboxValue.bind(this)} type="checkbox" value="Text" />
We can get check box value by declaring onChange={this.likeClicked} defaultChecked={false} on input element properties
constructor(props){
super(props)
this.likeClicked = this.likeClicked.bind(this)
}
likeClicked(){
console.log(event.target.checked, event.target.id);
}
render(){
return (
<div className='px-3'>
<div className='item-header item-wrapper cirle'>
<input
type="checkbox"
onChange={this.likeClicked}
defaultChecked={false}
className="checkbox"
id={`checkbox_${this.props.product.sku}`}
/>
<label htmlFor={`checkbox_${this.props.product.sku}`}>
<HeartIcon className="heart-svg"></HeartIcon>
</label>
</div>
</div>
);
}
One liner:
onChange={e => doSomethingWithValue( e.currentTarget.checked )}