How to Validate an Email address in React using functional components? - reactjs

I am working on a React project in that project I have a form, In that form I am trying to do
Validation for an email address, but I don't know how to apply all these.
What I am expecting is, In input tag if I type mark, then If I go to another Input tag it has to
Show me some kind of message above Input tag like this, please enter a valid email address.
This is Form.js
import React from 'react';
import './Form.css';
const Form = () => {
const validation = (email) => {
const result = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return result.test(String(email).toLowerCase());
}
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<div className='mainForm'>
<form>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" />
</div>
<div className="form-group">
<label htmlFor="exampleInputPassword1">Password</label>
<input type="password" className="form-control" id="exampleInputPassword1" />
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Form

I think those are basic problem in all JS code base, you need to catch the input event, using onChange, onBlur, On...etc and bind those event to your react class, like
return <input type=”email” name=”email” value={this.state.email}
onChange={this.handleChange.bind(this)}/>
then on the handleChange you can call the email validation
handleChange(event){
var email = event.target.value;
// do what ever you want
validation(email);
}

Related

Create a table and take data from json file in react js

I have the following fields in react js from which I should be able to perform crud operation with json file but have no idea how the Json file is created. Only I know is how to make UI. So, it would be very grateful if some would teach me how to do that. My code up to now:
App.js
import React from 'react'
const App = () => {
return (
<div>
<h3>Create Table</h3>
<hr />
<form className='form'>
<label className= "layout">Layout:</label>
<input
type= "text"
placeholder="select layout"
/>
<label className="name"> Name:</label>
<input
placeholder="Input Name"
/>
<label className = "capacity">Capacity:</label>
<input
type= "text"
placeholder="Enter Number Of Capacity"
/>
<label className= "status">Status:</label>
<input className= "input"
type="checkbox"
/>
<label className="Image">Image:</label>
<button className = "bttn">Choose File</button>
<p className = "para">No file choosen</p>
<button className= "btn">Create Table</button>
<button className= "button">Cancel</button>
</form>
</div>
)
}
export default App
All I want to know is how to create the fake data for all layouts, names, capacity and images to be able to choose and be able to display it in a table.
here is an example of crud in Jsonplaceholder: https://codesandbox.io/s/ey0w4?file=/src/index.js
I hope it's useful, if you faced any problem, let me know

How to call a function in a Reusable component in React

Hi I am working on a React project in my project one button is coming soo many times. So I created one component for Button and I am reusing that component where ever I get a button. Now the problem is when I am trying to apply onClick function to that Button component, my function is not working so please help me to resolve this issue.
This is Button Component Button.js
import React from "react";
import "./Button.css";
const Button = () => {
return (
<div>
<button className="btn btn-primary">Show login button</button>
</div>
);
};
export default Button;
This is Button.css, I have written nothing in this
This is App.js
import React, { useState } from "react";
import Button from "./Button/Button";
import "./App.css";
const App = () => {
const [hideForm, setHideForm] = useState(false);
const showLoginForm = () => {
setHideForm(true);
};
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-4">
{hideForm ? (
<div className="loginform">
<form>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter email"
></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Enter password"
></input>
</div>
<button type="submit" className="btn btn-primary mt-3">
Submit
</button>
</form>
</div>
) : (
<div className="signupform">
<form>
<div className="form-group">
<label htmlFor="firstname">Firstname</label>
<input
type="text"
className="form-control"
id="firstname"
placeholder="Enter firstname"
></input>
</div>
<div className="form-group">
<label htmlFor="lastname">Lastname</label>
<input
type="text"
className="form-control"
id="lastname"
placeholder="Enter lastname"
></input>
</div>
<div className="form-group">
<label htmlFor="email">Email</label>
<input
type="email"
className="form-control"
id="email"
placeholder="Enter email"
></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
className="form-control"
id="password"
placeholder="Enter password"
></input>
</div>
<button type="submit" className="btn btn-primary mt-3">
Submit
</button>
</form>
</div>
)}
<div className="buttons mt-3">
<Button onClick={() => showLoginForm()}></Button>
</div>
</div>
</div>
</div>
);
};
export default App;
const Button = ({handleClick}) => {
return (
<div>
<button onClick={handleClick} className='btn btn-primary'>Show login button</button>
</div>
)
}
Use It like this:
<Button handleClick={()=>anyFunc()}/>
or
<Button handleclick={anyFunc}/>
``
You can pass the Parent's on click event to child as a props and when you click on the child component's button event that is being declared on the parent's component can be called. Here is how you can do it:
Code on the Parent Component:
const myClick =()=>{
// on click will be called here when button will be pressed
}
<Button onClick={this.myClick}></Button>
Code on the Child Component:
<button onClick={this.props.myClick}>Click Here</button>

Scoping during Login with React and react-redux-firebase

I am using react-redux-firebase for authentication and user management.Once users login, I want to navigate the user to their dashboard with an url of 'dahboard/userId.' When the user authenticate firebase gives us a response that has the user's ID there. The problem is when I attempt to complete a nav request via 'this.history.push('dahsboard/uid') I keep getting an error that says 'this' is undefined. I'm pretty sure it is a scoping issue but I cannot figure out exactly how I need to structure the code to solve the problem.
I have already tried to store the uid as a const. I have also tried chaining another async funciton to the request. Either this.props is undefined or the uid is undefined.
onSubmit = (e) => {
e.preventDefault();
// this.props.signIn(this.state);
this.props.firebase.login(this.state)
.then(function(res){
const userId = res.user.user.uid;
console.log(userId);
this.props.push('/dashboard/userId');
// ! Scoping issue - How to get 'props' in or userId out of this scope
})
.catch(
err => console.log(err.message),
)
}
render() {
const authError = this.props.authError;
return(
<div className="container">
<div className="row">
<div className="col-sm-9 col-md-7 col-lg-5 mx-auto">
<div className="card card-signin my-5">
<div className="card-body">
<div className = "red-text center">
{authError ? <p> {authError.message} </p> : null}
</div>
<h5 className="card-title text-center">Sign In</h5>
<form className="form-signin" onSubmit={this.onSubmit}>
<div className="form-label-group">
<label>Email address
<input type="email" id="inputEmail" className="form-control" placeholder="Email address" value={this.state.email} onChange={this.onChangeEmail} required autoFocus />
</label>
</div>
<div className="form-label-group">
<label>Password
<input type="password" id="inputPassword" className="form-control" placeholder="Password"
value={this.state.password}
onChange={this.onChangePassword}
required />
</label>
</div>
<div className="custom-control custom-checkbox mb-3">
<input type="checkbox" className="custom-control-input" id="customCheck1" />
<label className="custom-control-label" >Remember password
</label>
</div>
<button className="btn btn-lg btn-primary btn-block text-uppercase" type="submit">Sign in</button>
<hr className="my-4" />
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default compose(
//map firebase redux to props
firebaseConnect((props) => {
}),
connect(
//map redux-state to props
(state) => ({
userId: state.firebase.auth.uid,
authError: state.firebase.authError,
auth: state.firebase.auth
})
)
)(Login)
You need to use withRouter from "react-router" like so:
export default withRouter(connect(mapStateToProps, {
...
})(App));
Then it will be accessible through this.props;
You can also pass history through props from App if you have a nested component like so:
<NestedComponent history={this.props.history}/>

"Expected an assignment but found an expression"

I'm working on a project with my classmates, but while trying to load this page in react I get the error: "Expected an assignment or function call and instead saw an expression" that's appeared on several of her pages. I looked into it and it seems to be a warning that ES Lint throws out, but I'm unsure of how to fix it for my particular issue. Any help would be appreciated.
Code Snippet::
import React from "react";
import './LoginPage.css';
import GlobalNav from '../../components/GlobalNav';
import GlobalFooter from '../../components/GlobalFooter/GlobalFooter';
const LoginPage = props => {
<div>
<GlobalNav />
<h1 className="uk-text-center blueText">login</h1>
<div className="uk-container"/>
<form className="authorForm uk-width-1-2#m uk-align-center uk-form-stacked">
<p className="uk-text-lead">Login and add some Highlights of your own.</p>
<p className="uk-text-center redText"><span uk-icon="bolt"></span></p>
<fieldset className="uk-fieldset">
<div className="form-group">
<div className="uk-margin">
<label className="uk-form-label" for="form-stacked-select">* Email:</label>
<div className="uk-inline uk-width-1-1">
<span className="uk-form-icon uk-form-icon-flip blueText" uk-icon="icon: world"></span>
<input className="uk-input" id="email" name="email" type="text"></input>
</div>
</div>
<div className="uk-margin">
<label className="uk-form-label" for="form-stacked-select">* Password:</label>
<div className="uk-inline uk-width-1-1">
<span className="uk-form-icon uk-form-icon-flip blueText" uk-icon="icon: lock"></span>
<input className="uk-input" id="password" name="password" type="text"></input>
</div>
</div>
<button className="uk-button uk-button-secondary redText uk-align-center" id="submit-btn"><span uk-icon="user"></span> login</button>
</div>
</fieldset>
</form>
<GlobalFooter />
</div>
}
export default LoginPage;
You forgot to enclose them in a return statement.
const LoginPage = props => {
// this is where you put your logic if needed before returning JSX codes
return (
<div>
// ...rest of the codes
</div>
);
};
or, you can simply do this, since you're using ES6 arrow function:
const LoginPage = props => (
<div>
// ...rest of the code
</div>
);

Input text in react form component does not allow text entry

I'm very new to react, and following a tutorial, made this Registration form (I just changed Bootstrap html with Materialize)
import React, {Component} from 'react';
class Register extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
errors: {}
};
this.handleChange = this.handleChange.bind(this);
}
handleChange (e) {
this.setState({
[e.target.name] : e.target.value
});
}
render() {
return (
<div>
<div className="row">
<div className="col s10 m6 offset-s1 offset-m3 ">
<form className="col s12 myform">
<h3 className="center"Register </h3>
<div className="row">
<div className="input-field col s12">
<input
id="email"
type="email"
value={this.state.email}
onChange = {this.handleChange}
/>
<label htmlFor="email">Email</label>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input
id="password"
type="password"
value={this.state.password}
onChange = {this.handleChange}
/>
<label htmlFor="password">Password</label>
</div>
</div>
<button className="btn mybtn waves-effect waves-light right" type="submit" name="action">Submit
<i className="mdi-content-send right"></i>
</button>
</form>
</div>
</div>
</div>
);
}
}
export default Register;
The problem is that I can not enter anything into the form and get no error in the console. So got really preplexed. Appreciate your hints.
As you have written:
handleChange (e) {
this.setState({
[e.target.name] : e.target.value // This line I mean.
});
}
So you just need to assign name prop to input tag because you have written e.target.name and your input name is available in the state but not available in input props.
So do it like this:
- Email input
<input
name="email"
id="email"
type="email"
value={this.state.email}
onChange = {this.handleChange}
/>
- Password input
<input
name="email"
id="email"
type="email"
value={this.state.email}
onChange = {this.handleChange}
/>
I hope it will be helped you and enjoy of react

Resources