Skip to content Skip to sidebar Skip to footer

Mapping Array Of Objects In Reactjs To Create Login Form

Im currently trying to create a login form in ReactJS (which does not have any backend and is relying on a Users.js file for input. My App.js looks something like this: import Reac

Solution 1:

Getting accustomed with most common array prototype methods ( like .some() ) would help a lot with solving those kinds of problems.

exportconst users = [
    { id: 0, name: 'user1', password: 'asd1' },
    { id: 0, name: 'user2', password: 'asd2' },
    { id: 0, name: 'user3', password: 'asd3' },
];

Then your postDetails would need to look like this:

import { users } from'...';

// ...postDetails() {
    const isUserValid = users.some(user => {
        const username = this.state.userName;
        const password = this.state.password;
        return user.name === username && user.password === password;
    });
    this.setState({ message: isUserValid });
};

Solution 2:

There is the functhion which try to find a user first and then if we find object with same name we check the password. If something isn't valid the function returns false otherwise it returns true

const users =[
  {id:1,name:"mahesh",password:"mahesh123"},
  {id:2,name:"abc",password:"abc123"}
]

constvalidation = (login, password) => {
  const user = users.find(user => login === user.name) // find the user with same nameif (typeof user !== 'undefined') { // check the user. If we didn't find a object with same name, user will be undefined return user.password === password // if passwords match it returns true
  }
  returnfalse
}

console.log(validation('mahesh', 'mahesh123'))
console.log(validation('abc', 'abc123'))
console.log(validation('abc', 'sffh'))
console.log(validation('abdsawec', 'abc123'))

Post a Comment for "Mapping Array Of Objects In Reactjs To Create Login Form"