I am trying to print "Hello" onto the screen when the add button is clicked. But it is not showing. Thank you in advance for any answers you may have!
import React, { Component } from 'react';
import './App.css';
import './Login.jsx';
import './Navbar.jsx';
class MainPage extends Component {
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
</div>
</div>
</div>
</div>
);
}
addTask = () => {
return (
<div>
<h2>Hello</h2>
</div>
)
}
}
export default MainPage;
Returning an HTML in an onClickEvent make no sense, where are the result going to be displayed?
I would manage it with a state, something like this
class MainPage extends Component {
this.state = {
buttonPress:false
}
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
{{this.state.buttonPress? <h2>Hello</h2> : <span/>}}
</div>
</div>
</div>
</div>
);
}
addTask = () => {
this.setState({buttonPress:true});
}
}
export default MainPage;
Where would the function return the "Hello" code?
import React, { Component } from 'react';
import './App.css';
import './Login.jsx';
import './Navbar.jsx';
class MainPage extends Component {
state = {
showMessage: false
}
addTask= () => {
this.setState({showMessage: true});
};
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
{this.state.showMessage && <div>
<h2>Hello</h2>
</div>}
</div>
</div>
</div>
</div>
);
}
}
export default MainPage;
Try this code instead, I created a state which tracks the visibility of the div.
More information here:
How do I display text on button click in React.js
You should use state
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props)
this.state = {testVarible: null}
}
render() {
return (
<div>
<div className="main-container">
<h1 style={{textDecoration:'underline'}}>Tasks</h1>
<div className="input-group mb-3">
<input type="text" id="task" className="form-control" placeholder="New Task"/>
<div id="name"></div>
<div className="input-group-append">
<button id="btn" className="btn btn-success" onClick={this.addTask}>Add</button>
</div>
</div>
</div>
{this.state.testVarible}
</div>
);
}
addTask = () => {
this.setState({testVarible: (
<div>
<h2>Hello</h2>
</div>
)});
}
}
export default App;
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
This question already has an answer here:
Problem in redirecting programmatically to a route in react router v6
(1 answer)
Closed 11 months ago.
This is the my login.js page code I want redirect the new page after click the button. I tried several methods but problem not solve. All things are work correctly. but I don't know how to link the page after the api return result in loginClick function. I Added this line in the code refer some tutorial but its not work.
this.props.history.push('/add');
I am new to the react js, I don't know about the react well. please help me.
import React,{Component} from 'react';
import { variables } from '../../Variables';
export class Login extends Component{
constructor(props){
super(props);
this.state={
login:[],
name:"",
password:"",
redirect: false
}
}
changelogindetailsname = (e)=>{
this.setState({name:e.target.value})
}
changelogindetailspass = (e)=>{
this.setState({password:e.target.value})
}
loginClick(){
fetch(variables.API_URL+'login',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
name:this.state.name,
password:this.state.password
})
})
.then(res=>res.json())
.then((result)=>{
alert(result);
this.props.history.push('/add');
},(error)=>{
alert('Faild');
})
}
render(){
const{
name,
password
}=this.state;
return(
<div>
<center>
<h1></h1>
<hr/>
<h3>Welcome Back !</h3>
<p></p>
<div className="container">
<br/>
<br/>
<br/>
<div className="row">
<div className="col">
</div>
<div className="col">
</div>
<div className="col-4">
<style>{"\ .rr{\ float:left;\ }\ "} </style>
<style>{"\ .bb{\ float:right;\ }\ "} </style>
<div className="mb-3">
<label className="form-label rr d-flex"> Username</label>
<div className="input-group input-group-lg">
<input type="text" className="form-control " id="formGroupExampleInput" placeholder="Username"
value={name}
onChange={this.changelogindetailsname}/>
</div>
</div>
<div className="mb-3">
<label className="form-label rr d-flex">Password</label>
<div className="input-group input-group-lg">
<input type="password" className="form-control" id="formGroupExampleInput2" placeholder="Password"
value={password}
onChange={this.changelogindetailspass}/>
</div>
</div>
<div className="d-flex mb-3">
Forgot your password?
</div>
<div className="col">
<div className="form-check rr">
<input className="form-check-input" type="checkbox" value="" id="flexCheckDefault"/>
<label className="form-check-label" htmlFor="flexCheckDefault">
Remember me
</label>
</div>
</div>
<div className="col">
<button type="button" className="btn btn-success bb"
onClick={()=>this.loginClick() } >Login</button>
</div>
<br/>
<br></br>
<hr/>
<p>Don't have an account?</p>
<div className="mb-3">
<button type="button" className="btn btn-light d-flex"
>Sign up for Muessoze</button>
</div>
</div>
<div className="col">
</div>
<div className="col">
</div>
</div>
</div>
</center>
</div>
)
}
}
Firstly you should import this:
import { useHistory } from 'react-router-dom';
then:
const history = useHistory();
after all, you can use this in your method:
loginClick(){
fetch(variables.API_URL+'login',{
method:'POST',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
},
body:JSON.stringify({
name:this.state.name,
password:this.state.password
})
})
.then(res=>res.json())
.then((result)=>{
alert(result);
history.push('/add');
},(error)=>{
alert('Faild');
})
}
Take a look at the react router API, if you want to use the this.props.history.push() method you will need to wrap your component with the withRouter HOC wrapper from the react dom api.
See : https://reactrouter.com/docs/en/v6/getting-started/tutorial
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 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)
I have a ReactJs component. handleSubmit is not called when my form is submitted. I am using meteorJs as my backend and ReactJs as my frontend library. I don't know where is the problem. I tried commenting out everything except input tag but didn't work.
import React, {Component} from 'react';
export default class ConfessionPoster extends Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
}
//handle form submit
handleSubmit(event) {
event.preventDefault();
console.log("We are in handle");
console.log(this.state.value);
}
handleInputChange(event) {
event.preventDefault();
// const target = event.target;
// const confessionValue = target.value;
// const confessionName = target.name;
//
// this.setState({[confessionName]: confessionValue});
// console.log(this.state.confessionText);
this.setState({value: event.target.value});
console.log(this.state.value);
}
render() {
return (
<div id="confession-poster" className="modal">
<div className="modal-content">
<div className="row">
<div className="col s1">
<i className="material-icons prefix">account_circle</i>
</div>
<div className="col s11">
<h6>Kiran Kumar Chaudhary</h6>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<div className="row confession-area">
<div className="input-field col s12">
<label htmlFor="confession-textarea">Your Confession</label>
<textarea id="confession-textarea" className="materialize-textarea" value={this.state.value} onChange={this.handleInputChange}/>
</div>
</div>
<div className="row">
<div className="col s12">
<i className="material-icons">photo_camera</i>
<i className="material-icons">link</i>
<i className="material-icons">location_on</i>
</div>
</div>
<div className="row">
<div className="input-field col s12">
<input type="checkbox" className="filled-in" id="hide-my-identity" defaultChecked/>
<label htmlFor="hide-my-identity">Hide my Identity</label>
</div>
</div>
<div className="row">
<input className="btn" type="submit" value="Post"/>
</div>
</form>
</div>
</div>
);
}
}