my form not submitting so where is the problem - reactjs

as you see my form not submit i can't see where is the problem i search but all the solution i found i already made it so what else can be the problem when i try to use console it don't show like it doesn't enter the submit function at all
this is the pieces in my component that work with form
const [editMyText, setEditMyText] = useState({
editIsActive: false,
textValue: body,
});
const inputRef = useRef(null);
const handleSaveEdit = (e) => {
setEditMyText({
editIsActive: false,
textValue: inputRef.current.value,
});
// updatePost(_id, textValue);
};
const handleOnSubmit = (e) => {
e.preventDefault();
console.log('done 1');
updatePost(_id, textValue);
console.log('done 2');
};
{body !== null && !editIsActive ? (
<p
className='card-text'
onClick={(e) => auth.user._id === user && handleEditText(e)}
>
{textValue}
</p>
) : (
<form
className='edit-post-form'
onSubmit={(e) => handleOnSubmit(e)}
>
<textarea
className='edit-text'
defaultValue={textValue}
ref={inputRef}
/>
<button
className='btn btn-raised btn-danger mr-2'
onClick={(e) => handleCloseEdit(e)}
>
Close
</button>
<button
type='submit'
className='btn btn-raised btn-success'
onClick={(e) => handleSaveEdit(e)}
>
Save
</button>
</form>
)}

Related

setting two states with onClick

I am trying to disable one of the button, when clicked but it is not working. onClick is changing two states, one for the text and one to disable the button.
const [loading, setLoading] = useState();
const [disable, setDisable] = useState(false);
return (
<div>
<p>Data is {loading ? "Loading" : "not Loading"} </p>
<button
onClick={() => {
setLoading(true);
setDisable(true);
}}
disabled={disable}
>
ON
</button>
<button
onClick={() => {
setLoading(false);
setDisable(false);
}}
disabled={disable}
>
OFF
</button>
</div>
);
you should set the "OFF" button to disabled={!disable}
<button
onClick={() => {
setLoading(false);
setDisable(false);
}}
disabled={!disable}
>
OFF
</button>

get input value using custom numbers in react

i have custom numpad and input box and i want that when user click any number it shows in input field.
<div class="grid-container">
<button class="grid-item" onClick={inputNumKey}>1</button>
<button class="grid-item" onClick={inputNumKey}>2</button>
<button class="grid-item" onClick={inputNumKey}>3</button>
<button class="grid-item" onClick={inputNumKey}>4</button>
<button class="grid-item" onClick={inputNumKey}>5</button>
<button class="grid-item" onClick={inputNumKey}>6</button>
<button class="grid-item" onClick={inputNumKey}>7</button>
<button class="grid-item" onClick={inputNumKey}>8</button>
<button class="grid-item" onClick={inputNumKey}>9</button>
<button class="grid-item" onClick={inputNumKey}>*</button>
<button class="grid-item" onClick={inputNumKey}>0</button>
<button class="grid-item" onClick={inputNumKey}>#</button>
</div>
this is my numpad jsx code.
<div className="input-box-ad">
<input onChange={changeTime} name="hour" value={updatedHour} />
<input onChange={changeTime} name="minute" value={updatedMinute} />
<input onChange={changeTime} name="second" value={updatedSecond} />
</div>
this is input fields i want values of this button.
for more details i have codesandbox also - https://codesandbox.io/s/fancy-frog-l5uo2
const activeInput = { "background-color": "#BBFFCC" };
const Numbers = () => {
const [hour, setHour] = useState("00");
const [minute, setMinute] = useState("00");
const [second, setSecond] = useState("00");
const [timeType, setTimeType] = useState("hour");
const press = (k) => {
const [value, setter] =
timeType === "hour"
? [hour, setHour]
: timeType === "minute"
? [minute, setMinute]
: [second, setSecond];
setter((value.charAt(value.length - 1) || "0") + k);
};
return (
<div>
<div class="grid-container">
<button onClick={() => press("1")}>1</button>
<button onClick={() => press("2")}>2</button>
<button onClick={() => press("3")}>3</button>
<button onClick={() => press("4")}>4</button>
<button onClick={() => press("5")}>5</button>
<button onClick={() => press("6")}>6</button>
<button onClick={() => press("7")}>7</button>
<button onClick={() => press("8")}>8</button>
<button onClick={() => press("9")}>9</button>
<button onClick={() => press("*")}>*</button>
<button onClick={() => press("0")}>0</button>
<button onClick={() => press("#")}>#</button>
</div>
<div className="input-box-ad">
<input name={"hour"} value={hour} size={2}
onClick={() => setTimeType("hour")}
onChange={(e) => setHour(e.target.value)}
style={timeType === "hour" ? activeInput : {}}
/>
:
<input name={"minute"} value={minute} size={2}
onClick={() => setTimeType("minute")}
onChange={(e) => setMinute(e.target.value)}
style={timeType === "minute" ? activeInput : {}}
/>
:
<input name={"second"} value={second} size={2}
onClick={() => setTimeType("second")}
onChange={(e) => setSecond(e.target.value)}
style={timeType === "second" ? activeInput : {}}
/>
</div>
</div>
);
};
This is going to be very difficult to manage. I don't know why do you need the buttons to enter input you can do it with the keyboard.
If you do it with a keyboard then it will be easy.
const[updatedHour,setUpdatedHour] = useState();
function changeHour(e){
setUpdatedHour(e.target.value)
}
<input onChange={changeHour} name="hour" value={updatedHour} />
Do the same for all input boxes.
Still, if you want to do it with buttons here is a hint.
function inputNumKey(e){
console.log(e.target.textContent)
}

Todo list Reverse state to false on click onclick

I am trying to reverse a state to true or false when user is clicking the cancel button.
The full project is available on sandbox via the link below. I am new to react developing and struggling with state. Can someone help, please?
To see what i mean by the above, please enter some input and click add
https://codesandbox.io/s/eloquent-feather-gc88n?file=/src/header/header.js
Thank Leo
Update your handleCancelClick function to this:
handleCancelClick = (e) => {
setIsEditing((prevState) => !prevState)
console.log('Cancel edit', isEditing)
}
Few more amends that you might need:
In skillist.js:
<EditSkillsForm
inputs={inputs}
isEditing={isEditing}
setIsEditing={setISEditing}
onCancelClick={handleCancelClick}
onUpdateInput={handleUpdateInput}
onCurrentInput={currentInput}
/>
In editSkillsForm.js, we get isEditing and setIsEditing props also :
const EditSkillsForm = ({
handleUpdateInput,
inputs,
handleCancelClick,
setCurrentSkill,
isEditing,
setIsEditing
}) => {
Full file code (just in case):
editSkillsForm.js:
import React, { useState } from "react";
const EditSkillsForm = ({
handleUpdateInput,
inputs,
handleCancelClick,
setCurrentSkill,
isEditing,
setIsEditing
}) => {
//const [ currentSkill, setCurrentSkill ] = useState({});
// const [isEditing, setIsEditing] = useState(true);
// const [ onSubmitEditing, SetOnSubmitEditing ] = useState("")
function handleEditInputChange(e) {
setCurrentSkill(e.target.value);
}
handleCancelClick = (e) => {
setIsEditing(false);
console.log("Cancel edit", isEditing);
};
return (
<>
{isEditing ? (
<div>
<h4>Edit Skill</h4>
<input
className="mb-2"
size="lg"
onChange={handleEditInputChange}
type="text"
name="Update skill"
placeholder="Update skill"
value={inputs}
/>
<button className="btn btn-primary mx-2" onClick={handleUpdateInput}>
Update
</button>
<button onClick={() => handleCancelClick()}>Cancel</button>
</div>
) : null}
{/* <div>
<h4>Edit Skill</h4>
<input
className="mb-2"
size="lg"
onChange={handleEditInputChange}
type="text"
name="Update skill"
placeholder="Update skill"
value={inputs}
/>
</div> */}
{/* <input
className="mb-2"
size="lg"
onChange={handleEditInputChange}
type="text"
name="Update skill"
placeholder="Update skill"
value={inputs}
/> */}
{/* <button className="btn btn-primary mx-2">Update</button> */}
{/* <button onClick={() => handleCancelClick()}>Cancel</button> */}
</>
);
};
export default EditSkillsForm;

my onclick function overlapped with submit handler

when i put onClick event the form does not validate and if i delete onClick event the form does not want to submit
so recently i just start a new project with kendo react. on this project i tried to create customize grid where i can add new lines, edit or remove.
<form style={{ width: '1000px' }} onSubmit={this.handleSubmit} >
<div className="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<div className="k-animation-container">
<DropDownList
defaultValue={this.state.productInEdit.Programto || ''}
onChange={this.onDialogInputChange}
name="Programto"
required={true}
data={this.prog}
/>
</div>
</div>
</div>
<div className="row" >
<DialogActionsBar>
<Button
className="k-button"
onClick={this.props.cancel}
>
Cancel
</Button>
<Button className="mt-3" type="submit" primary={true} onClick={this.props.save} > Save </Button>
</DialogActionsBar>
</div>
</form>
and this is the event for validation
handleSubmit = (event) => {
event.preventDefault();
this.setState({ success: true });
setTimeout(() => { this.setState({ success: false }); }, 3000);
}
and submit code i create it on different page, so i need to call the event with this.props.save;
save = () => {
const dataItem = this.state.productInEdit;
const products = this.state.products.slice();
if (dataItem.ProductID === undefined) {
products.unshift(this.newProduct(dataItem));
} else {
const index = products.findIndex(p => p.ProductID === dataItem.ProductID);
products.splice(index, 1, dataItem);
}
this.setState({
products: products,
productInEdit: undefined
});
}
i tried to call save event inside the handleSubmit but still not working

Final form array fields async validation

I am trying to implement async validation react-final-form-array. But its returning promise but not showing error at all.
I took reference of this code for asnyc validate and created my own version with final form array here.
Form:
<Form
onSubmit={onSubmit}
mutators={{
...arrayMutators
}}
initialValues={{ customers: [{ placeholder: null }] }}
validate={formValidate}
render={({
handleSubmit,
mutators: { push, pop }, // injected from final-form-arrays above
pristine,
reset,
submitting,
values,
errors
}) => {
return (
<form onSubmit={handleSubmit}>
<div>
<label>Company</label>
<Field name="company" component="input" />
</div>
<div className="buttons">
<button type="button" onClick={() => push("customers", {})}>
Add Customer
</button>
<button type="button" onClick={() => pop("customers")}>
Remove Customer
</button>
</div>
<FieldArray name="customers" validate={nameValidate}>
{({ fields }) =>
fields.map((name, index) => (
<div key={name}>
<label>Cust. #{index + 1}</label>
<Field
name={`${name}.firstName`}
component={testInput}
placeholder="First Name"
/>
<Field
name={`${name}.lastName`}
component={testInput}
placeholder="Last Name"
/>
<span
onClick={() => fields.remove(index)}
style={{ cursor: "pointer" }}
>
❌
</span>
</div>
))
}
</FieldArray>
<div className="buttons">
<button type="submit" disabled={submitting || pristine}>
Submit
</button>
<button
type="button"
onClick={reset}
disabled={submitting || pristine}
>
Reset
</button>
</div>
<pre>
nameValidate Function:{"\n"}
{JSON.stringify(nameValidate(values.customers), 0, 2)}
</pre>
<pre>
Form errors:{"\n"}
{JSON.stringify(errors, 0, 2)}
</pre>
<pre>
Form values:{"\n"}
{JSON.stringify(values, 0, 2)}
</pre>
</form>
);
}}
/>
Validate Function:
const duplicateName = async value => {
await sleep(400);
if (
~["john", "paul", "george", "ringo"].indexOf(value && value.toLowerCase())
) {
return { firstName: "name taken!" };
}
};
const nameValidate = values => {
if (!values.length) return;
const errorsArray = [];
values.forEach(value => {
if (value) {
let errors = {};
if (!value.firstName) errors.firstName = "First Name Required";
if (Object.keys(errors).length === 0) {
errors = duplicateName(value.firstName);
console.log("errors", errors);
}
errorsArray.push(errors);
}
});
return errorsArray;
};
Okay, you're mixing the validation in a way that's not allowed. You can't embed a Promise inside an array of errors, the whole validation function must return a promise. Here's the fixed version. The await duplicateName() is the important bit.
const nameValidate = async values => {
if (!values.length) return
return await Promise.all(
values.map(async value => {
let errors = {}
if (value) {
if (!value.firstName) errors.firstName = 'First Name Required'
if (Object.keys(errors).length === 0) {
errors = await duplicateName(value.firstName)
}
}
console.error(errors)
return errors
})
)
}

Resources