score:3
you need to do something in the following place:
const addname = (event) => {
event.preventdefault();
const nameobject = {
name: newname
};
setpersons([...persons, nameobject]);
};
use .find()
on the persons
array to find the particular name already existing and add the condition before setpersons
is executed.
if (persons.find(p => p.name === newname)) {
window.alert("name already exists!");
return false;
}
a code like above will work.
import react, { usestate } from "react";
const app = () => {
const [persons, setpersons] = usestate([{ name: "arto hellas" }]);
const [newname, setnewname] = usestate("");
const addname = (event) => {
event.preventdefault();
if (persons.find((p) => p.name === newname)) {
window.alert("name already exists!");
return false;
}
const nameobject = {
name: newname
};
setpersons([...persons, nameobject]);
};
const handlenamechange = (event) => {
setnewname(event.target.value);
};
return (
<div>
<h2>phonebook</h2>
<form onsubmit={addname}>
<div>
name: <input value={newname} onchange={handlenamechange} />
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<h2>numbers</h2>
{persons.map((person) => (
<p key={person.name}>{person.name}</p>
))}
</div>
);
};
export default app;
demo: https://codesandbox.io/s/nervous-poitras-i3stw?file=/src/app.js:0-958
the above code shows an ugly error alert using the normal window alert. if you want a better error like this:
you can use the following code, by setting a state:
import react, { usestate } from "react";
import "./styles.css";
const app = () => {
const [persons, setpersons] = usestate([{ name: "arto hellas" }]);
const [newname, setnewname] = usestate("");
const [error, seterror] = usestate(false);
const addname = (event) => {
event.preventdefault();
if (persons.find((p) => p.name === newname)) {
seterror(true);
return false;
}
const nameobject = {
name: newname
};
setpersons([...persons, nameobject]);
};
const handlenamechange = (event) => {
setnewname(event.target.value);
};
return (
<div>
<h2>phonebook</h2>
<form onsubmit={addname}>
{error && <p classname="error">user already exists.</p>}
<div>
name: <input value={newname} onchange={handlenamechange} />
</div>
<div>
<button type="submit">add</button>
</div>
</form>
<h2>numbers</h2>
{persons.map((person) => (
<p key={person.name}>{person.name}</p>
))}
</div>
);
};
export default app;
and here's our style.css
:
.error {
background-color: red;
color: #fff;
padding: 5px;
}
demo: https://codesandbox.io/s/vibrant-tree-wsou2?file=/src/app.js
score:0
you can use the find method to search for a person with the newname
. please check the below code-snippet:
const addname = (event) => {
event.preventdefault()
const nameobject = {
name: newname,
}
let personalreadyexists = persons.find(person => person.name === newname);
if (personalreadyexists) {
alert('person with that name already exists');
// any other operations (like clearing user input in the form, etc..)
}
else {
setpersons([...persons, nameobject])
}
}
score:1
first add field to check name exists or not:
const nameexists = react.usememo(() => {
return persons.some(item => item.name === newname);
}, [newname, persons])
then disable button and show message if name exists:
<div>
{nameexists && <p>name {newname} already exists!</p>}
<button type="submit" disabled={nameexists} >add</button>
</div>
also, make sure you clear name when you add new name:
const addname = (event) => {
...
setnewname('')
}
const app = () => {
const [ persons, setpersons ] = react.usestate([ { name: 'arto hellas' }])
const [ newname, setnewname ] = react.usestate('')
const addname = (event) => {
event.preventdefault()
const nameobject = {
name: newname,
}
setpersons([...persons,nameobject]);
setnewname('')
}
const handlenamechange = (event) => {
setnewname(event.target.value)
}
const nameexists = react.usememo(() => {
return persons.some(item => item.name === newname);
}, [newname, persons])
return (
<div>
<h2>phonebook</h2>
<form onsubmit={addname} >
<div>
name: <input value={newname} onchange={handlenamechange} />
</div>
<div>
{nameexists && <p>name {newname} already exists!</p>}
<button type="submit" disabled={nameexists} >add</button>
</div>
</form>
<h2>numbers</h2>
{persons.map(person => (
<p key={person.name}>{person.name}</p>
))}
</div>
)
}
reactdom.render(<app />, document.getelementbyid('root'))
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
Source: stackoverflow.com
Related Query
- How do I prevent the user from being able to add names that already exist?
- prevent the user from being able to add names
- How do I prevent Material UI Dialog from being dismissed upon clicking the backdrop?
- How to prevent the onmouseleave event from being triggered outside the browser?
- Webpack - prevent font files (.woff, .eot, .ttf) in peer dependencies from being part of the build
- Styled Component - How to prevent a prop from being passed to the extended component?
- How to I prevent user from accessing the page of my react app directly by entering the URL, and redirect them back to login page
- Prevent user from go back to the login page when user logged in React js
- How to prevent the user from accessing other parts of the page until the customized alert box is closed?
- Prevent user from entering numbers but keep the alphabetical characters they have already entered
- How to prevent a simple React modal from being closed if you either start or end the click event inside the modal?
- Not able to access the animate.css's animation keyframe names from scss file
- react-beautiful-dnd: Prevent the rest of draggable items from reordering / moving up and replacing the item being dragged
- How can i get the values of actor names from the below given json. I am able to get rest of the values but not actor names
- Prevent child elements from being the target when parent element is clicked
- How to avoid letting an async thunk that is no longer useful (the app is not expecting it anymore) from being able to update the state?
- How can I prevent my array from being overwritten when setting the state?
- How to prevent a prop from being passed to the extended component?
- Prevent Menu From Closing When User Clicks the Input
- Ignore or prevent ESLint errors from breaking the build in a React project (create-react-project)
- How to prevent react from re-rendering the whole component?
- Using Lodash debounce in React to prevent requesting data as long as the user is typing
- How to prevent redux-persist from using LocalStorage before it has been allowed by the user?
- Prevent user from returning to previous screen StackNavigator
- In React, how to prevent a component's CSS import from applying to the entire app?
- How to avoid the useState function parameter (to get initial values) from being executed on every render?
- How to prevent React from re-rendering the whole component
- Preventing redux store value from being used again in the component
- How to prevent user from selecting date above end date in react-dates
- How to prevent User from creating duplicate values using React-Select Creatable?
More Query from same tag
- React setState inside componentDidUpdare leads to Maximum update depth exceeded
- ionic react type is not assignable
- React - infinite loop using get request when using useState hook
- How to make API calls using React, Redux in TypeScript
- Iterate over a object in reactjs
- React useState async updating and for-loop
- Cannot create a new reactJs application
- wrong class names on pages with different content rendered on client than on server
- Require a specific type of functional component as a prop in React with Typescript
- componentDidUpdate called twice every route change
- React executing code before the previous function call has finished
- Trying to render a full page video background in Next.js but getting blank page
- How to properly getItem with AsyncStorage in React Native?
- How to prevent image icon from being cut off?
- Are subsequent pages also crawl-able (SEO) when we change route in NextJs application?
- Async/Await not waiting
- Refresh a React Child Functional Component based on Async input from Parent
- How change Ant design Tooltip width
- how to have no enclosing tags with React?
- Issues with conditional rendering
- Cache busting with CRA React
- Clicking <Link> doesn't lose focus in react-router with require.ensure
- How to store all Functions in one file and inherit it in ReactJS
- Move text inside border
- Adding custom tag stops rendering of the page
- Listening for useState default value event
- How to map twice using Gatsby?
- Passing an object property through a variable in spread operator
- How to organize js code when you are using v8js engine (php) for prerending react component?
- how to show selected item in react js?