I am trying to create a button that add more input and remove input and when it remove the input it also clear all the data inside that input but the problem is when I remove that input but the data still stay. How can I fix that ?
Here is my code base:
const [inputs, setInputs] = useState(teamData.rules);
useEffect(() => {
setInputs(teamData.rules);
}, [teamData]);
// Add more input
const addInputs = () => {
setInputs([...inputs, { name: `rule-${inputs.length + 1}` }]);
};
// handle click event of the Remove button
const handleRemoveClick = (index) => {
const list = [...inputs];
list.splice(index, 1);
setInputs(list);
};
{inputs.map((data, index) => (
<div className="agreement-form-grid" key={index}>
<button
className="agreement-remove-button"
onClick={() => handleRemoveClick(index)}
>
<Remove />
</button>
<input
type="text"
defaultValue={teamData.rules[index]}
name={`rule_${index}`}
placeholder={`Rule ${index + 1}`}
onChange={handleChange}
/>
</div>
))}
{inputs.length !== 4 && (
<div className="team-agreement-add-rule">
<button type="submit" onClick={addInputs}>
<Add />
</button>
</div>
)}
Update question add handleChange function:
const handleChange = (event) => {
const { name, value } = event.target;
// Update state
setUpdateTeamData((prevState) => ({
...prevState,
[name]: value,
}));
}
Define another function in your parent component to clear the data like below,
const clearInput = (dataName) => {
setUpdateTeamData((prevState) => {
delete prevState[dataName];
return {
...prevState
}
});
}
In the child component, in the onClick of the remove button call this function as well
<button
className="agreement-remove-button"
onClick={() => { handleRemoveClick(index); clearInput(`rule_${index}`)}}
>
<Remove />
</button>
Before saving you can ignore empty inputs
Related
I have array of items and searching items function, that returns another array. When I delete or edit item finded items changes don't render, but when search string has another value React render changes.
I know that useEffect can resolve this problem, but dont what to put in callback.
How can resolve this problem?
export const ToDoList = (props: PropsType) => {
const [searchQuery, setSearchQuery] = useState('')
const searchedItems = useMemo(() => {
return props.ToDoData.filter(item => item.text.includes(searchQuery))
},
[searchQuery])
return (
{props.ToDoData.length ?
<>
<input
...
onChange={e => setSearchQuery(e.target.value)}
/>
<ItemsList
...
items={
searchQuery ?
searchedItems :
props.ToDoData
}
/>
</> :
...
}
)
}
export const ItemsList = (props: PropsType) => {
const [editedText, setEditedText] = useState('')
const onDeleteItem = (id: number) => {
props.dispatch(deleteItem(id))
},
onEditItemMode = (id: number, text: string) => {
props.dispatch(setEditMode(true, id))
setEditedText(text)
},
onEditText = (id: number) => {
props.dispatch(setEditedTextInItem(id, editedText))
props.dispatch(setEditMode(false, id))
setEditedText('')
},
onToggleCompletedStatus = (id: number, status: string) => {
...
}
return (
{props.items.length ?
props.items.map((object) => (
<div
className="Item"
key={object.id}
>
{props.inEditMode.some((id: number) => id === object.id) ?
<>
<input
value={editedText}
onChange={e => { setEditedText(e.currentTarget.value) }}
/>
<button onClick={() => onEditText(object.id)}>
Change text
</button>
</> :
<>
<div className="Item__textBlock">
<input
type='checkbox'
onClick={() => { onToggleCompletedStatus(object.id, object.status)}}
/>
<span className={
object.status === 'completed' ?
'completed' :
'in process'
}>
{object.text}
</span>
</div>
<div className="Item__buttonBlock">
<button
className="Item__button"
disabled={props.inEditMode.length !== 0}
onClick={() => onEditItemMode(object.id, object.text)}
>
<img src={editImg} />
</button>
<button
className="Item__button"
onClick={() => { onDeleteItem(object.id) }}
>
<img src={removeImg} />
</button>
</div>
</>
}
</div>
)) :
...
}
)
}
// This code creates a list that is ONLY updated when searchQuery is updated
const searchedItems = useMemo(() => {
return props.ToDoData.filter(item => item.text.includes(searchQuery))
}, [searchQuery]);
// This code creates the list every time the component renders,
// so it will always be correct
const searchedItems = props.ToDoData.filter(item => item.text.includes(searchQuery))
// If you absolutely need to optimize the render of this component
// This code will update the list whenever the reference for ToDoData is updated as well
const searchedItems = useMemo(() => {
return props.ToDoData.filter(item => item.text.includes(searchQuery))
}, [searchQuery, props.ToDoData]);
I want to disable the submit button on the form if the user enters a value that already exists in the task list.
'Todos' is the array that stores the list and I used 'some' to check if the input value is equal to some title. However, it doesn't work.
CODE
const [disable, setDisable] = useState(false);
const onFormSubimit = (event) => {
event.preventDefault();
if (!editTodo) { //mudar depois a condição
setTodos([...todos, {
id: uuidv4(),
title: input,
completed: false
}]);
setInput("");
} else {
updateTodo(input, editTodo.id, editTodo.completed);
}
}
const handleInputChange = (event) => {
let inputValue = event.target.value;
setInput(inputValue);
getInputValue(inputValue);
}
const getInputValue = (inputValue) => {
let some = todos.some(item => item.title === inputValue);
if (some!=disable) {
setDisable(true);
}
}
return (
<form onSubmit={onFormSubimit}>
<input type='text' name='text' placeholder='Insira o nome da tarefa' className='task-input' value={input} onChange={handleInputChange} required></input>
<button type='submit' className='button-add' disabled={getInputValue} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
</form>
);
}
Your button state is dependent on input (the variable set by setInput) and todos. So the best way to handle this is via an useEffect with a dependency array.
useEffect(() => {
// Array.some returns a boolean
setDisable(todos.some(item => item.title === input))
}, [todos, input]);
Your button code
<button type='submit' className='button-add' disabled={disable} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
You can also directly use this logic in button like below. In this case there is no need of useEffect
<button type='submit' className='button-add' disabled={todos.some(item => item.title === input)} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
First, change your button with the code below (as it should be disabled ={disable}, not disabled={getInputValue}). And getInputValue as following.
<button type='submit' className='button-add' disabled={disable} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
const getInputValue = (inputValue) => {
if (todos.some((item) => item.title === inputValue)) {
setDisable(true);
} else {
setDisable(false);
}
};
Hi i am working on a React application where there are four inputs.when a user add an input the element will be added to the wrapper.In the following code add operation works fine but remove operation is not working properly ,it is not removing the corresponding element.Another problem the values on the inputs fields not present when the component re-renders.so experts guide me how i can achieve removing the corresponding row when the remove button is clicked and the input values should not be reset when the component re-renders
So when I refresh the page and click to remove an input it will clear all other input data. How can I fix this problem ?
Update added full component to question:
const Agreement = (props) => {
const { agreement, editable, teamData, teamId, fetchTeamData } = props;
const [editing, setEditing] = useState(false);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [showErrors, setShowErrors] = useState(false);
const [errorsArr, setErrorsArr] = useState();
const initialFormState = {
rule_0: teamData.rule_0,
rule_1: teamData.rule_1,
rule_2: teamData.rule_2,
rule_3: teamData.rule_3,
creator: teamData.User.public_user_id,
};
const [updateTeamData, setUpdateTeamData] = useState(initialFormState);
const [inputs, setInputs] = useState(teamData.rules);
const handleChange = (event) => {
const { name, value } = event.target;
// Update state
setUpdateTeamData((prevState) => ({
...prevState,
[name]: value,
}));
};
// Add more input
const addInputs = () => {
setInputs([...inputs, { name: `rule-${inputs.length + 1}` }]);
};
// handle click event of the Remove button
const handleRemoveClick = (index) => {
const list = [...inputs];
list.splice(index, 1);
setInputs(list);
};
const clearInput = (dataName) => {
setUpdateTeamData((prevState) => {
delete prevState[dataName];
return {
...prevState,
};
});
};
const handleSubmit = async (event) => {
event.preventDefault();
setEditing(false);
// Send update request
console.log(updateTeamData);
const res = await axios.put(`/api/v1/teams/team/${teamId}`, updateTeamData);
// If no validation errors were found
// Validation errors don't throw errors, it returns an array to display.
if (res.data.validationErrors === undefined) {
// Clear any errors
setErrorsArr([]);
// Hide the errors component
setShowErrors(false);
// Call update profiles on parent
fetchTeamData();
} else {
// Set errors
setErrorsArr(res.data.validationErrors.errors);
// Show the errors component
setShowErrors(true);
}
};
const handleCancel = () => {
setEditing(false);
};
useEffect(() => {
if (agreement === "default") {
setTitle(defaultTitle);
setInputs(teamData.rules);
} else {
setTitle(agreement.title ?? "");
}
}, [agreement, teamData]);
return (
<div className="team-agreement-container">
{!editing && (
<>
<h4 className="team-agreement-rules-title">{title}</h4>
{editable && (
<div className="team-agreement-rules">
<EditOutlined
className="team-agreement-rules-edit-icon"
onClick={() => setEditing(true)}
/>
</div>
)}
<p className="team-agreement-rules-description">{description}</p>
{teamData.rules.map((rule, index) => (
<div className="team-agreement-rule-item" key={`rule-${index}`}>
{rule ? (
<div>
<h4 className="team-agreement-rule-item-title">
{`Rule #${index + 1}`}
</h4>
<p className="team-agreement-rule-item-description">
- {rule}
</p>
</div>
) : (
""
)}
</div>
))}
</>
)}
{/* Edit rules form */}
{editing && (
<div className="team-agreement-form">
{showErrors && <ModalErrorHandler errorsArr={errorsArr} />}
<h1>Rules</h1>
{inputs.map((data, idx) => {
return (
<div className="agreement-form-grid" key={`${data}-${idx}`}>
<button
type="button"
className="agreement-remove-button"
onClick={() => {
handleRemoveClick(idx);
clearInput(`rule_${idx}`);
}}
>
<Remove />
</button>
<input
type="text"
placeholder={`Rule ${idx + 1}`}
defaultValue={teamData.rules[idx]}
name={`rule_${idx}`}
onChange={handleChange}
/>
</div>
);
})}
{inputs.length < 4 && (
<div className="team-agreement-add-rule">
<button type="submit" onClick={addInputs}>
<Add />
</button>
</div>
)}
<div className="div-button">
<button className="save-button" onClick={handleSubmit}>
Save
</button>
<button className="cancel-button" onClick={handleCancel}>
Cancel
</button>
</div>
</div>
)}
</div>
);
};
export default Agreement;
Hi i am working on a React application where there are four options.when a user select an option corresponding input element will be added to the wrapper.In the following code add operation works fine but remove operation is not working properly ,it is not removing the corresponding element.Another problem the values on the inputs fields not present when the component re-renders.so experts guide me how i can acheive removing the corresponding row when the remove button is clicked and the input values should not be reset when the component re-renders.
But when I submit the input it will appear my data perfectly and when i restart the page and just click into edit and hit submit with the defaultValue it just clear all the data and send back to my backend with undefined value like this: [ undefined, undefined, undefined, undefined ]
Here is my full component:
const Agreement = (props) => {
const { agreement, editable, teamData, teamId, fetchTeamData } = props;
const [editing, setEditing] = useState(false);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [showErrors, setShowErrors] = useState(false);
const [errorsArr, setErrorsArr] = useState();
const initialFormState = {
rule_0: teamData.rules.rule_0,
rule_1: teamData.rules.rule_1,
rule_2: teamData.rules.rule_2,
rule_3: teamData.rules.rule_3,
creator: teamData.User.public_user_id,
};
const [updateTeamData, setUpdateTeamData] = useState(initialFormState);
const [inputs, setInputs] = useState(teamData.rules);
const handleChange = (event) => {
const { name, value } = event.target;
// Update state
setUpdateTeamData((prevState) => ({
...prevState,
[name]: value,
}));
};
// Add more input
const addInputs = () => {
setInputs([...inputs, { name: `rule_${inputs.length + 1}` }]);
};
// handle click event of the Remove button
const removeInputs = (index) => {
const list = [...inputs];
list.splice(index, 1);
setInputs(list);
};
const clearInput = (dataName) => {
setUpdateTeamData((prevState) => {
delete prevState[dataName];
return {
...prevState,
};
});
};
const handleSubmit = async (event) => {
event.preventDefault();
setEditing(false);
// Send update request
const res = await axios.put(`/api/v1/teams/team/${teamId}`, updateTeamData);
// If no validation errors were found
// Validation errors don't throw errors, it returns an array to display.
if (res.data.validationErrors === undefined) {
// Clear any errors
setErrorsArr([]);
// Hide the errors component
setShowErrors(false);
// Call update profiles on parent
fetchTeamData();
} else {
// Set errors
setErrorsArr(res.data.validationErrors.errors);
// Show the errors component
setShowErrors(true);
}
};
const handleCancel = () => {
setEditing(false);
};
useEffect(() => {
if (agreement === "default") {
setTitle(defaultTitle);
setInputs(teamData.rules);
} else {
setTitle(agreement.title ?? "");
}
}, [agreement, teamData]);
console.log("teamData.rules", teamData.rules);
console.log("inputs", inputs);
return (
<div className="team-agreement-container">
{!editing && (
<>
<h4 className="team-agreement-rules-title">{title}</h4>
{editable && (
<div className="team-agreement-rules">
<EditOutlined
className="team-agreement-rules-edit-icon"
onClick={() => setEditing(true)}
/>
</div>
)}
<p className="team-agreement-rules-description">{description}</p>
{teamData.rules.map((rule, index) => (
<div className="team-agreement-rule-item" key={`rule-${index}`}>
{rule ? (
<div>
<h4 className="team-agreement-rule-item-title">
{`Rule #${index + 1}`}
</h4>
<p className="team-agreement-rule-item-description">
- {rule}
</p>
</div>
) : (
""
)}
</div>
))}
</>
)}
{/* Edit rules form */}
{editing && (
<div className="team-agreement-form">
{showErrors && <ModalErrorHandler errorsArr={errorsArr} />}
<h1>Rules</h1>
{inputs.map((data, idx) => {
return (
<div className="agreement-form-grid" key={`${data}-${idx}`}>
<button
type="button"
className="agreement-remove-button"
onClick={() => {
removeInputs(idx);
clearInput(`rule_${idx}`);
}}
>
<Remove />
</button>
<input
name={`rule_${idx}`}
onChange={handleChange}
value={teamData.rules[idx]}
/>
</div>
);
})}
{inputs.length < 4 && (
<div className="team-agreement-add-rule">
<button type="submit" onClick={addInputs}>
<Add />
</button>
</div>
)}
<div className="div-button">
<button className="save-button" onClick={handleSubmit}>
Save
</button>
<button className="cancel-button" onClick={handleCancel}>
Cancel
</button>
</div>
</div>
)}
</div>
);
};
export default Agreement;
How can I fix this error?
My thought is the problem is around [inputs, setInputs]
Try this
<input
//..
onChange={(event) => handleChange(event.target.value)}
//..
/>
then in your "handleChange" function
const handleChange = (event) => {
const { name, value } = event;
//....
};
Application:
Search bar with two text input fields (input1, input2)
Three buttons: SearchX, SearchY, Clear results
Both the searches can take input1 and input2 as parameters to give two different results.
There's a result component which takes both the inputs, action and renders the search component depending on the action.
function TestComponent() {
const [input1, setInput1] = useState('');
const [input2, setInput2] = useState('');
const [action, setAction] = useState(null);
const onInput1Change = evt => setInput1(evt.target.value);
const onInput2Change = evt => setInput2(evt.target.value);
return (
<div>
<input type="text" value={input1} onChange={onInput1Change} />
<input type="text" value={input2} onChange={onInput2Change} />
<button type="button" onClick={() => setAction('SearchX')}>
SearchX
</button>
<button type="button" onClick={() => setAction('SearchY')}>
SearchY
</button>
<button type="button" onClick={() => setAction('Clear results')}>
Clear results
</button>
<ResultComponent input1={input1} input2={input2} action={action} />
</div>
);
}
function ResultComponent({ input1, input2, action }) {
if (action === 'SearchX') {
return <SearchX input1={input1} input2={input2} />;
}
if (action === 'SearchY') {
return <SearchY input1={input1} input2={input2} />;
}
if (action === 'Clear results') {
return null;
}
return null;
}
function SearchX({ input1, input2 }) {
const [result, setResult] = useState(null);
useEffect(() => {
// Fetch and process X-way to get the result. Using timeout to simulate that
const id = window.setTimeout(() => setResult(`Search X result with inputs: ${input1}, ${input2}`), 3000);
return () => window.clearInterval(id);
}, [input1, input2]);
return <div>{result}</div>;
}
function SearchY({ input1, input2 }) {
const [result, setResult] = useState(null);
useEffect(() => {
// Fetch and process Y-way to get the result. Using timeout to simulate that
const id = window.setTimeout(() => setResult(`Search Y result with inputs: ${input1}, ${input2}`), 3000);
return () => window.clearInterval(id);
}, [input1, input2]);
return <div>{result}</div>;
}
ReactDOM.render(<TestComponent />, document.getElementById('root'));
Problem:
We want the search to initiate only when a button is clicked. With below code, after the first search result, as soon as you change your input, the result component expectedly re-renders thereby initiating search again without button click
Steps to reproduce the problem:
Enter "input1" in first text box
Enter "input2" in second text box
Hit on "SearchX"
After 3 seconds you should see something like "Search X result with inputs: input1, input2"
Change any of the input boxes. Need not press enter.
After 3 seconds, the result would change without button click
Possible option:
Planning to use React.memo hook to compare action prop before updating the result component. Action prop can only change on button clicks and hence can solve the problem.
Question:
Is there any other way (any other hooks etc.) to solve the problem?
Or is there any other process/design that I can follow to avoid memo ?
You could, upon input interaction, reset the action back to null. This will clear out the current result and not trigger a "search".
function TestComponent() {
const [input1, setInput1] = useState('');
const [input2, setInput2] = useState('');
const [action, setAction] = useState(null);
const onInput1Change = evt => {
setInput1(evt.target.value);
setAction(null);
};
const onInput2Change = evt => {
setInput2(evt.target.value)
setAction(null);
};
return (
<div>
<input type="text" value={input1} onChange={onInput1Change} />
<input type="text" value={input2} onChange={onInput2Change} />
<button type="button" onClick={() => setAction('SearchX')}>
SearchX
</button>
<button type="button" onClick={() => setAction('SearchY')}>
SearchY
</button>
<button type="button" onClick={() => setAction(null)}>
Clear results
</button>
<ResultComponent input1={input1} input2={input2} action={action} />
</div>
);
}
EDIT Use html5 forms to save input and set action upon submit. When inputs are interacted with the inputs in state aren't updated until form is submitted.
function TestComponent() {
const [input1, setInput1] = useState("");
const [input2, setInput2] = useState("");
const [action, setAction] = useState(null);
return (
<div>
<form
id="searchX"
onSubmit={e => {
e.preventDefault();
setInput1(e.target.inputX.value);
setAction("SearchX");
}}
/>
<form
id="searchY"
onSubmit={e => {
e.preventDefault();
setInput2(e.target.inputY.value);
setAction("SearchY");
}}
/>
<input id="inputX" form="searchX" type="text" />
<input id="inputY" form="searchY" type="text" />
<input form="searchX" type="submit" value="SearchX" />
<input form="searchY" type="submit" value="SearchY" />
<button type="button" onClick={() => setAction(null)}>
Clear results
</button>
<ResultComponent input1={input1} input2={input2} action={action} />
</div>
);
}
Also, setting the "clear results" button action back to null saves a conditional check in ResultComponent, which simplifies to:
function ResultComponent({ input1, input2, action }) {
if (action === 'SearchX') {
return <SearchX input1={input1} input2={input2} />;
}
if (action === 'SearchY') {
return <SearchY input1={input1} input2={input2} />;
}
return null;
}
You can use refs to inputs and only update state on button click.
export default function TestComponent() {
const [input1, setInput1] = useState("");
const [input2, setInput2] = useState("");
const [action, setAction] = useState(null);
const input1Ref = useRef(null);
const input2Ref = useRef(null);
const onButtonClick = () => {
if (input1Ref.current) {
setInput1(input1Ref.current.value);
}
if (input2Ref.current) {
setInput2(input2Ref.current.value);
}
};
const onSearchXClick = () => {
onButtonClick();
setAction("SearchX");
};
const onSearchYClick = () => {
onButtonClick();
setAction("SearchX");
};
return (
<div>
<input ref={input1Ref} type="text" />
<input ref={input2Ref} type="text" />
<button type="button" onClick={onSearchXClick}>
SearchX
</button>
<button type="button" onClick={onSearchYClick}>
SearchY
</button>
<button type="button" onClick={() => setAction("Clear results")}>
Clear results
</button>
<ResultComponent input1={input1} input2={input2} action={action} />
</div>
);
}