I am trying to implement react into a small piece of a website, but for some reason it is not rendering what so ever. I am using node, express, React, and handlebars.
landing.handlebars:
<section class="section section-dark">
<div id="root"></div>
<script type="text/jsx" src="index.js"></script>
index.jsx:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
App.jsx:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: null,
email: null,
message: null,
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
handleSubmit(event) {
event.preventDefault();
}
render() {
return (
<div className="App">
<h2 className="bottom">Send Message!</h2>
<form onSubmit={this.handleSubmit} className="bottom">
<div className="form-group">
<label for="exampleInputEmail1">Email address:</label>
<input type="email" onChange= {this.handleChange} value = {this.state.email} className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div classNameName="form-group">
<label for="exampleInputPassword1">Name:</label>
<input type="text" onChange= {this.handleChange} value={this.state.name} className="form-control" id="exampleInputPassword1" placeholder="Name" />
</div>
<div className="form-group">
<label for="exampleTextarea">Message:</label>
<textarea onChange= {this.handleChange} value={this.state.message} className="form-control" id="exampleTextarea" rows="3"></textarea>
</div>
<button type="submit" value="submit" className="btn btn-primary"> <i
className="fa fa-paper-plane" aria-hidden="true"></i> Send</button>
</form>
</div>
);
}
}
export default App;
It shows no sort of jsx file in the network tag at all besides the ones that are necessary (Jquery, bootstrap, etc)
Related
I am learning React now . I have made a page called as App.js which is a Login Page.I have navigated it to another page App2.js . The navigation process is being done , but I am not able to see the contents in that page .
Here is my Code:-
App.js
import React from "react";
import "./App.css";
//import './App2'
import { Navigate } from "react-router-dom";
function App() {
const [goToContact, setGoToContact] = React.useState(false);
if (goToContact) {
return <Navigate to="/App2" />;
}
return (
<div className="LoginPage">
<div className="topnav">
<h1 className="Heading">E-Commerce App</h1>
</div>
<div className="card">
<div className="container">
<h1 className="SignUp">Sign Up</h1>
<form>
<label for="email" className="email">
<b>Email</b>
</label>
<br />
<input type="email" name="email" placeholder="Enter your email" />
<br />
<label for="psw" className="Password">
<b>Password</b>
</label>
<br />
<input
type="password"
name="Password"
placeholder="Enter your password"
/>
<br />
<label for="psw-repeat">
<b>Repeat Password</b>
</label>
<br />
<input
type="password"
name="Repeat Password"
placeholder="Repeat Password"
/>
<br />
<input type="checkbox" name="Remember Me" className="remember" />
<label for="vehicle1"> Remember Me</label>
<br />
<div class="clearfix">
<button
type="button"
class="cancelbtn"
onClick={() => {
setGoToContact(true);
}}
>
Login
</button>
<button type="submit" class="signupbtn">
Sign Up
</button>
</div>
</form>
</div>
</div>
</div>
);
}
export default App;
App2.js
import React from "react";
function App2() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
export default App2;
``
This is the file structure of my React Application. It is under a src file.
Output of App.js
Output of App2.js
#KarthikKK Phil's comment is what you're looking for. Look into the concept of routing and you will see that you will have one component which will decide which route (component) to render.
First you will need to setup the router:
In your index.js:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
<BrowserRouter>
{/* The rest of your app goes here */}
</BrowserRouter>,
root
);
Then your App.js:
function App() {
return (
<Routes>
<Route path="/" element={<App1 />} />
<Route path="/app2" element={<App2 />} />
</Routes>
);
}
const App1 = () => {
return (
<div className="LoginPage">
<div className="topnav">
<h1 className="Heading">E-Commerce App</h1>
</div>
<div className="card">
<div className="container">
<h1 className="SignUp">Sign Up</h1>
<form>
<label htmlFor="email" className="email">
<b>Email</b>
</label>
<br/>
<input type="email" name="email" placeholder="Enter your email"/>
<br/>
<label htmlFor="psw" className="Password">
<b>Password</b>
</label>
<br/>
<input
type="password"
name="Password"
placeholder="Enter your password"
/>
<br/>
<label htmlFor="psw-repeat">
<b>Repeat Password</b>
</label>
<br/>
<input
type="password"
name="Repeat Password"
placeholder="Repeat Password"
/>
<br/>
<input type="checkbox" name="Remember Me" className="remember"/>
<label htmlFor="vehicle1"> Remember Me</label>
<br/>
<div className="clearfix">
<button
type="button"
className="cancelbtn"
onClick={() => {
navigate('/app2');
}}
>
Login
</button>
<button type="submit" className="signupbtn">
Sign Up
</button>
</div>
</form>
</div>
</div>
</div>
)
}
const App2 = () => {
return (
<div>
<h1>Hello</h1>
</div>
);
}
export default App;
Full documentation (worth spending a couple hours really understanding this):
https://reactrouter.com/en/main/start/overview
This is index.js, replace this with yours, if you haven't made any change in index.js.
import React from "react";
import { createRoot } from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import "./index.css";
import App from "./App";
import App2 from "./App2";
import reportWebVitals from "./reportWebVitals";
const router = createBrowserRouter([
{
path: "/",
element: <App />,
},
{
path: "/App2",
element: <App2 />,
},
]);
createRoot(document.getElementById("root")).render(
<RouterProvider router={router} />
);
reportWebVitals();
You have to define the route before you use it. You can define it with what component you need render on that route.
Documentation: https://reactrouter.com/en/main/start/overview
I am creating an application where I am getting a parameter from a function and if the parameter equals true I would render a new route instead.
I know how to use react-router-dom as to render new routes you would use something like this
<Link to="/login">Login</Link>
But I don't know how to call it in a function.
function functionName(success){
if (success){
//What do I write here?
// Something like go to path="/login"
}
}
Thank you
(edit)
import { useContext, useState, useEffect } from "react";
import { AuthContext } from "../../Context Api/authenticationAPI";
import { FaUserPlus } from "react-icons/fa";
import { Link, useHistory } from "react-router-dom";
import Alerts from "./Alerts";
const Register = () => {
const history = useHistory();
const { addUser } = useContext(AuthContext);
const data = useContext(AuthContext).data;
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
useEffect(() => {
console.log(data);
if (data.success) {
history.push("/login");
}
}, [data]);
return (
<div className="row mt-5">
<div className="col-md-6 m-auto">
<div className="card card-body">
<h1 className="text-center mb-3">
<i>
<FaUserPlus />
</i>{" "}
Register
</h1>
<Alerts />
<form>
<div className="mb-2">
<label>Name</label>
<input
type="name"
id="name"
name="name"
className="form-control"
placeholder="Enter Name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="mb-2">
<label>Email</label>
<input
type="email"
id="email"
name="email"
className="form-control"
placeholder="Enter Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="mb-2">
<label>Password</label>
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Create Password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button
onClick={(e) => {
e.preventDefault();
addUser({ name, email, password });
}}
className="btn btn-primary col-12"
>
Register
</button>
<p className="lead mt-4">
Have An Account? <Link to="/login">Login</Link>
</p>
</form>
</div>
</div>
</div>
);
};
export default Register;
import React from "react";
import { Link } from "react-router-dom";
import { FaSignInAlt } from "react-icons/fa";
const Login = () => {
return (
<div className="row mt-5">
<div className="col-md-6 m-auto">
<div className="card card-body">
<h1 className="text-center mb-3">
<i>
<FaSignInAlt />
</i>{" "}
Login
</h1>
<div className="mb-2">
<label>Email</label>
<input
type="email"
id="email"
name="email"
className="form-control"
placeholder="Enter Email"
/>
</div>
<div className="mb-2">
<label>Password</label>
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Enter Password"
/>
</div>
<button className="btn btn-primary col-12">Login</button>
<p className="lead mt-4">
No Account? <Link to="/register">Register</Link>
</p>
</div>
</div>
</div>
);
};
export default Login;
You can make use of the history object and programmatically navigate using history.push()
import { useHistory } from 'react-router-dom'
const history = useHistory();
function functionName(success){
if (success) {
history.push('/login')
}
}
Reference
useHistory Hook
At the moment I try to write in the form and save it in the state, I get this error:
Warning: A component is changing an uncontrolled input of type text to
be controlled. Input elements should not switch from uncontrolled to
controlled (or vice versa). Decide between using a controlled or
uncontrolled input element for the lifetime of the component.
import React from 'react';
class ExerciseNew extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state)
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
return (
<div className="container">
<form
onSubmit={this.handleSubmit}
>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="title"
name="title"
onChange={this.handleChange}
value={this.state.title}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="description"
name="description"
onChange={this.handleChange}
value={this.state.description}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="img"
name="img"
onChange={this.handleChange}
value={this.state.img}
/>
</div>
<div className="form-row">
<div className="col">
<input
type="text"
className="form-control"
placeholder="leftColor"
name="leftColor"
onChange={this.handleChange}
value={this.state.leftColor}
/>
</div>
<div className="col">
<input
type="text"
className="form-control"
placeholder="rightColor"
name="rightColor"
onChange={this.handleChange}
value={this.state.rightColor}
/>
</div>
</div>
<button
type="submit"
className="btn btn-primary"
>
Submit
</button>
</form>
</div>
)
}
}
export default ExerciseNew;
I find it curious because I am following the documentation of react, along with this video in Spanish.
I tried using babeljs and the features of ES7 so as not to have to create the constructor, so I did something like this:
import React from 'react';
class ExerciseNew extends React.Component {
state = {}
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state)
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
return (
<div className="container">
<form
onSubmit={this.handleSubmit}
>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="title"
name="title"
onChange={this.handleChange}
value={this.state.title}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="description"
name="description"
onChange={this.handleChange}
value={this.state.description}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="img"
name="img"
onChange={this.handleChange}
value={this.state.img}
/>
</div>
<div className="form-row">
<div className="col">
<input
type="text"
className="form-control"
placeholder="leftColor"
name="leftColor"
onChange={this.handleChange}
value={this.state.leftColor}
/>
</div>
<div className="col">
<input
type="text"
className="form-control"
placeholder="rightColor"
name="rightColor"
onChange={this.handleChange}
value={this.state.rightColor}
/>
</div>
</div>
<button
type="submit"
className="btn btn-primary"
>
Submit
</button>
</form>
</div>
)
}
}
export default ExerciseNew;
and still I get the same error.
Your form is already a controlled components.
You are getting warning beacuse, you have not initialized your state. You need to have each variable in state like,
this.state = {
title: '',
description: '',
img: '',
leftColor: '',
rightColor: ''
}
Note: A you are already using arrow function for handleSubmit & handleChange, you don't need to bind them in constructor,
this.handleChange = this.handleChange.bind(this); //not needed
this.handleSubmit = this.handleSubmit.bind(this); //not needed
Live Example:
class ExerciseNew extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "",
description: "",
img: "",
leftColor: "",
rightColor: "",
};
}
handleSubmit = (e) => {
e.preventDefault();
console.log(this.state)
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
return (
<div className="container">
<form
onSubmit={this.handleSubmit}
>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="title"
name="title"
onChange={this.handleChange}
value={this.state.title}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="description"
name="description"
onChange={this.handleChange}
value={this.state.description}
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
placeholder="img"
name="img"
onChange={this.handleChange}
value={this.state.img}
/>
</div>
<div className="form-row">
<div className="col">
<input
type="text"
className="form-control"
placeholder="leftColor"
name="leftColor"
onChange={this.handleChange}
value={this.state.leftColor}
/>
</div>
<div className="col">
<input
type="text"
className="form-control"
placeholder="rightColor"
name="rightColor"
onChange={this.handleChange}
value={this.state.rightColor}
/>
</div>
</div>
<button
type="submit"
className="btn btn-primary"
>
Submit
</button>
</form>
</div>
)
}
}
ReactDOM.render(
<ExerciseNew/>,
document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.development.js"></script>
I have made a bank account submit form. I want to save the data which is entered in the form into redux store. How can I take input value from form and store it in redux store variable ?
My client.js file has redux store and form.js is the component from which I need to get the input values.
client.js:
import { combineReducers, createStore } from 'redux';
const addUserReducer = (state={}, action) => {
switch(action.type){
case: "CHANGE_FIRSTNAME"{
state = {...state, firstname:action.payload }
break;
}
case: "CHANGE_LASTNAME"{
state = {...state, lastname:action.payload }
break;
}
case: "CHANGE_EMAILID"{
state = {...state, emailid:action.payload }
break;
}
case: "CHANGE_IBAN"{
state = {...state, iban:action.payload }
break;
}
case: "CHANGE_BANKNAME"{
state = {...state, bankname:action.payload }
break;
}
}
return state;
}
const reducers = combineReducers({
addUser:addUserReducer
})
const store = createStore(reducers);
store.subscribe(() => {
console.log('Store changed', store.getState());
})
store.dispatch({type: "CHANGE_FIRSTNAME", payload:"Will"});
store.dispatch({type: "CHANGE_LASTNAME", payload:"Groot"});
store.dispatch({type: "CHANGE_EMAILID", payload:"xyz#gmail.com"});
store.dispatch({type: "CHANGE_IBAN", payload:3234243242});
store.dispatch({type: "CHANGE_BANKNAME", payload:"XYZ"});
form.js:
import React, { Component } from "react";
import "./form.css";
class Form extends Component {
render() {
return (
<div>
<div id="center">
<form>
<div className="form-group">
<label for="firstname">First Name:</label>
<input type="firstname" className="form-control" id="firstname" />
</div>
<div className="form-group">
<label for="lastname">Last Name:</label>
<input type="lastname" className="form-control" id="lastname" />
</div>
<div className="form-group">
<label for="email">Email address:</label>
<input type="email" className="form-control" id="email" />
</div>
<div className="form-group">
<label for="bankacc">IBAN:</label>
<div id="deletebank" className="items">
<input type="bankacc" className="form-control" id="bankacc" />
<button type="button" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash" />
</button>
</div>
</div>
<div className="form-group">
<label for="bankname">Bank Name:</label>
<input type="bankname" className="form-control" id="bankname" />
</div>
<div className="form-group">
<button type="button" className="btn addbank">
+ Add bank account
</button>
</div>
<div className="form-group">
<button type="button" class="btn btn-success">
Submit
</button>
</div>
</form>
</div>
</div>
);
}
}
export default Form;
Screenshot of my form:
I would recommend react-redux to connect your components with redux store, however it is still doable without it:
Create action creators that will update specific variable in the store:
import { bindActionCreators } from "redux";
const updateFirstName = name => ({ type: "CHANGE_FIRSTNAME", payload: name });
const updateLastName = lastName => ({
type: "CHANGE_LASTNAME",
payload: lastName
});
const updateEmail = email => ({ type: "CHANGE_EMAILID", payload: email });
const updateIban = iban => ({ type: "CHANGE_IBAN", payload: iban });
const updateBankName = bankName => ({
type: "CHANGE_BANKNAME",
payload: bankName
});
Now bind your action creators with dispatch, so calling actionCreators.updateFirsName('something') will actually dispatch an action to the store.
export const actionCreators = bindActionCreators(
{
updateFirstName,
updateLastName,
updateEmail,
updateIban,
updateBankName
},
store.dispatch
);
Now you only need to call each store-updating function whenever theres an change on the input:
import React, { Component } from "react";
import "./form.css";
import { actionCreators } from "/path/to/store";
class Form extends Component {
render() {
return (
<div>
<div id="center">
<form>
<div className="form-group">
<label for="firstname">First Name:</label>
<input
type="firstname"
className="form-control"
id="firstname"
onChange={e => actionCreators.updateFirstName(e.target.value)}
/>
</div>
<div className="form-group">
<label for="lastname">Last Name:</label>
<input
type="lastname"
className="form-control"
id="lastname"
onChange={e => actionCreators.updateLastName(e.target.value)}
/>
</div>
<div className="form-group">
<label for="email">Email address:</label>
<input
type="email"
className="form-control"
id="email"
onChange={e => actionCreators.updateEmail(e.target.value)}
/>
</div>
<div className="form-group">
<label for="bankacc">IBAN:</label>
<div id="deletebank" className="items">
<input
type="bankacc"
className="form-control"
id="bankacc"
onChange={e => actionCreators.updateIban(e.target.value)}
/>
<button type="button" class="btn btn-default btn-sm">
<span class="glyphicon glyphicon-trash" />
</button>
</div>
</div>
<div className="form-group">
<label for="bankname">Bank Name:</label>
<input
type="bankname"
className="form-control"
id="bankname"
onChange={e => actionCreators.updateBankName(e.target.value)}
/>
</div>
<div className="form-group">
<button type="button" className="btn addbank">
+ Add bank account
</button>
</div>
<div className="form-group">
<button type="button" class="btn btn-success">
Submit
</button>
</div>
</form>
</div>
</div>
);
}
}
export default Form;
I'm trying to use bootstrap 4 to display an error of an input from a form.
Everything It's working but once I click the "SignUp" button with the empty form, no red error is display it. So the ""has-danger"" class from Bootstrap 4 doesn't work. I would like to know if the is any other way to user the error class from Bootstap 4.
import React from 'react';
import PropTypes from 'prop-types';
import map from 'lodash/map';
import classnames from 'classnames';
class SignUpForm extends React.Component {
constructor(props) {
super(props);
this.state = {
firstname: '',
lastname: '',
username: '',
password: '',
email: '',
errors: {},
isLoading: false
}
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
this.setState({errors: {}, isLoading: true});
this.props.userSignUpRequest(this.state).then(() => {}, ({data}) => this.setState({errors: data, isLoading: false}));
}
render() {
const {errors} = this.state;
return (
<form onSubmit={this.onSubmit}>
<div className={classnames('form-group', {'has-danger': errors.firstname})}>
<label className="form-control-label">
First Name
</label>
<input value={this.state.firstname} onChange={this.onChange} type="text" name="firstname" className="form-control form-control-danger" id="inputDanger1"/> {errors.firstname && <span className="help-block">{errors.firstname}</span>}
</div>
<div className="form-group has-danger">
<label className="form-control-label">
Last Name
</label>
<input value={this.state.lastname} onChange={this.onChange} type="text" name="lastname" className="form-control form-control-danger"/> {errors.lastname && <span className="help-block">{errors.lastname}</span>}
</div>
<div className="form-group">
<label className="control-label">
Username
</label>
<input value={this.state.username} onChange={this.onChange} type="text" name="username" className="form-control"/> {errors.username && <span className="help-block">{errors.username}</span>}
</div>
<div className="form-group">
<label className="control-label">
Password
</label>
<input value={this.state.password} onChange={this.onChange} type="text" name="password" className="form-control"/> {errors.password && <span className="help-block">{errors.password}</span>}
</div>
<div className="form-group">
<label className="control-label">
Email
</label>
<input value={this.state.email} onChange={this.onChange} type="text" name="email" className="form-control"/> {errors.email && <span className="help-block">{errors.email}</span>}
</div>
<div className="text-left">
<small>By clicking Submit, I agree that I have read and accepted the
Terms and conditions
</small>
</div>
<div className="form-group mt-1">
<button disabled={this.state.isLoading} className="btn btn-primary btn-lg">Sign Up</button>
</div>
</form>
);
}
}
SignUpForm.propTypes = {
userSignUpRequest: PropTypes.func.isRequired
}
export default SignUpForm;