I have a checkbox and want to change the class of the button:
let able = 'btn btn-secondary" disabled';
function handleChange(e) {
let isChecked = e.target.checked;
if (isChecked===true){
able = '"btn btn-primary"';
console.log(able);
}
console logs "btn btn-primary" which is correct , however the button is not changing at all
and in the return:
<input class="form-check-input" type="checkbox" id="gridCheck" onChange={e => handleChange(e)} />
<button type='submit' class={able}>Register</button>
Can someone please let me know what I am doing wrong?
Thank you in advance
In React.js you should use state. I suggest you learn about the basics of React. For your case, this should do the trick:
JSX
import React, { useState } from 'react';
const [isChecked, setChecked] = useState(false);
const handleChange = (e) => {
setChecked(e.target.checked);
}
HTML
<input class="form-check-input" type="checkbox" id="gridCheck" onChange={e => handleChange(e)} />
<button type='submit' disabled={!isChecked} class={`btn btn-${isChecked ? 'primary' : 'secondary'}`}>Register</button>
Related
i am sending data to make woocommerce graphql reigster a user, but sometimes it work some time it dont, speicalily once i succesful register a user, then right ahead to register again it wont register again. after i wait a while or refresh the page, it can be register again, is woocommerce graphql have somekind of delay system to prevent register spam, so i know is not my code problem. here is my code
const [username, setUsername] = useState('')
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [registerUser, { data, error, isLoading }] = client.useMutation((mutation, args: FormData) => {
const result = mutation.registerUser({
input: args,
})
console.log('REsult', result)
return result.user
})
const handleSubmit = async (event) => {
event.preventDefault()
await registerUser({
args: {
username,
email,
password,
},
})
.catch((error) => {
console.log('error:', error)
})
.then((response) => {
console.log('response:', response)
})
}
useEffect(() => {
console.log(data)
setUsername('')
setEmail('')
setPassword('')
}, [data])
here is my html:
return (
<div className="ps-page--default">
<form className="ps-form--auth" id="register__tab">
<div className="ps-tabs">
<div id="tab-2">
<div className="form-group form-group--space">
<input
className="form-control"
name="username"
id="register__tab--username"
type="text"
placeholder="What should we call you ?"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</div>
<div className="form-group form-group--space">
<input
className="form-control"
name="email"
id="register__tab--email"
type="email"
placeholder="Enter your email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="form-group form-group--space">
<input
className="form-control"
name="password"
id="register__tab--password"
type="text"
placeholder="Create a password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="ps-form__desc">
<p>Your personal data will be used to support your experience throughout this website, to manage access to your account, and for other purposes described in our privacy policy.
</p>
</div>
<div className="form-group submit">
<button type="submit" className="ps-btn ps-btn--fullwidth ps-btn--black" disabled={isLoading} onClick={handleSubmit}>
{isLoading ? 'Signing up...' : 'Sign up'}
</button>
</div>
</div>
</div>
</form>
</div>
)
do anyone know what do i miss ? or is just part of woocommerce graphql setting ?
the only error show on my console.log are this
[gqty] Warning! No data requested.
resolved2 # resolvers.mjs?c4ac:167
others are all my successful return
I've been trying to render {ingredients} with line breaks, each time the user presses Enter and keys in another ingredient. I've been getting all the user's inputs in one line e.g. grapeonionlettuce I'm not sure what, where or how to add code so that it'll have line breaks - tried using CSS too, by referencing the className return-ingredients-list and using white-space etc. but to no avail. Please help, thanks in advance, if possible.
//import { useState} from "react";
//import {Paper} from "#material-ui/core";
const {useState} = React;
const CRBUploadRecipe = () => {
const [recipeName, setRecipeName] = useState("");
const [selectedFile, setSelectedFile] = useState(undefined);
const [ingredients, setIngredients] = useState([]);
const handleEnterKeyPress = (e) => {
if(e.which === 13) {
const input = document.getElementById("ingredients");
setIngredients([input.value, ...ingredients])
console.log(ingredients)
}
};
return (
<div>
{/*<Paper elevation={12}>*/}
<div className="upload-recipe">
<form>
<label htmlFor="form-title" className="form-title">
Share to the Community <br/>
<input id="recipe-name" type="text" value={recipeName} placeholder="Recipe name"
onChange={e => setRecipeName(e.target.value)}
/>
</label>
<label htmlFor="upload-image" className="upload-image">
Upload image <br/>
<input id="upload-image" type="file" value={selectedFile}
onChange={e => setSelectedFile(e.target.files[0])}
/>
</label>
<label htmlFor="ingredients" className="ingredients">
Ingredients <br/>
<input id="ingredients" type="text" placeholder="Write ingredients"
onKeyPress={handleEnterKeyPress} />
</label>
<div className="return-ingredients-list">
{ingredients}
</div>
</form>
</div>
{/*</Paper>*/}
</div>
);
};
ReactDOM.render(
<div>
DEMO
<CRBUploadRecipe />
</div>,
document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />
<div id="ingredients"></div>
first of all don't use document.getElementById("ingredients") in react app.
second of all you can put each ingredient in paragraph or div;
import { useState} from "react";
import {Paper} from "#material-ui/core";
const CRBUploadRecipe = () => {
const [recipeName, setRecipeName] = useState("");
const [selectedFile, setSelectedFile] = useState(undefined);
const [ingredients, setIngredients] = useState([]);
const handleEnterKeyPress = (e) => {
if(e.which === 13) {
const input = e.target; // your handler already has access to input;
setIngredients((prev) => [input.value, ...prev])
console.log(ingredients)
}
}
return (
<Paper elevation={12}>
<div className="upload-recipe">
<form>
<label htmlFor="form-title" className="form-title">
Share to the Community <br/>
<input id="recipe-name" type="text" value={recipeName} placeholder="Recipe name"
onChange={e => setRecipeName(e.target.value)}
/>
</label>
<label htmlFor="upload-image" className="upload-image">
Upload image <br/>
<input id="upload-image" type="file" value={selectedFile}
onChange={e => setSelectedFile(e.target.files[0])}
/>
</label>
<label htmlFor="ingredients" className="ingredients">
Ingredients <br/>
<input id="ingredients" type="text" placeholder="Write ingredients"
onKeyPress={handleEnterKeyPress} />
</label>
<div className="return-ingredients-list">
{ingredients.map((ingridient, id) => (<p key={id}>{ingridient}</p>)}
</div>
</form>
</div>
</Paper>
);
}
export default CRBUploadRecipe;
I am using this module by HackerOne: https://reactdatepicker.com
After installing and importing the module to my Project i decided to pick the Select time component from the site.
My Code
import React, { Component } from "react";
import { Form, Button } from "react-bootstrap"
import DatePicker from "react-datepicker"
export default class AddEventModal extends Component {
constructor(props) {
super(props)
this.state = {
date: new Date()
}
}
render() {
return (
<Form>
<Form.Group controlId="formBasicEmail">
<Form.Label>Title <span style={{ color: "red" }}>*</span></Form.Label>
<Form.Control type="text" placeholder="Enter a Title" className="col-6" />
<Form.Text className="text-muted">
Enter a Title for your Event.
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicPassword">
<Form.Label>Description</Form.Label>
<Form.Control type="text" placeholder="Enter a Description" className="col-6" />
</Form.Group>
<DatePicker
selected={this.state.date}
onChange={newDate => this.setState({ date: newDate })}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
timeCaption="time"
dateFormat="MMMM d, yyyy h:mm aa"
/>
<Form.Group controlId="formBasicCheckbox">
<Form.Check type="checkbox" label="Check me out" />
</Form.Group>
<Button variant="success" type="submit">
Submit
</Button>
</Form>
);
}
}
My Output
https://i.stack.imgur.com/2L1Rv.png
It shouldn't be like this... The site has the working demo. What am I doing wrong?
EDIT: Answer is in the comments. I was missing a css import
Seems like I was missing a css import. Too bad the site didn't mention this clearly.
import "react-datepicker/dist/react-datepicker.css"
iam using the latest version of meteor & react. Yesterday I switched to the newest version of bootstrap. Before that everything worked just fine now I canĀ“t fix my (really noobish) problem.
import React, {Component} from 'react';
import { FormControl, , etc. } from 'react-bootstrap';
export default class Login extends Component {
login(event) {
event.preventDefault();
var username = this.refs.inputName.refs.input.value.trim();
var password = this.refs.inputPw.refs.input.value.trim();
Meteor.loginWithPassword(username, password, function (error) {
if (error) {
...
}
else {
FlowRouter.go('/c/' + Meteor.user().username);
}
});
this.refs.password.refs.input.value = "";
}
render() {
return (
<Row>
<Col xs={3} xsOffset={4}>
<form onSubmit={this.login.bind(this)}>
<FormGroup>
<ControlLabel>Willkommen</ControlLabel>
<FormControl
type="text"
placeholder="Benutzername"
ref="inputName"
name="username"/>
</FormGroup>
<FormGroup>
<FormControl
placeholder="Password"
ref="inputPw"
name="password"
type="password"/>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button bsStyle="primary" label="Login" id="loginButton" type="submit" active>Login</Button>
</Col>
</FormGroup>
</form>
</Col>
</Row>
);
}
In my previous solution I used a simple input form. Due to deprecation I switched to this formControl stuff. Now it seems that
<form onSubmit={this.login.bind(this)}>
login never gets called. Console.log(username) returns undefined.
Thanks in advance and many greetings.
//edit 1:
It seems like Iam not the only one with this problem.
React-bootstrap Form getValue not a function
This helped me a lot to find my solution:
import ReactDom from 'react-dom';
var username = ReactDom.findDOMNode(this.refs.inputName).value;
var password = ReactDom.findDOMNode(this.refs.inputPw).value;
I have this basic component and I want the textfield to be deactivated or activated whenever I click on a button. How can I achieve this?
This is my sample code:
import React from "react";
import Button from 'react-button'
const Typing = (props) => {
var disabled = "disabled";
var enabled = !disabled;
const handleUserInput = (event) => props.onUserInput(event.target.value);
const handleGameClik = (props) => {
disabled = enabled;
}
return(
<div>
<input
className = "typing-container"
value = {props.currentInput}
onChange = {handleUserInput}
placeholder=" ^__^ "
disabled = {disabled}/>
<Button onClick = {handleGameClik}> Start Game </Button>
<Button> Fetch Data </Button>
</div>
);
};
A simplified solution using state could look like this:
class Typing extends React.Component {
constructor(props) {
super(props);
this.state = { disabled: false }
}
handleGameClik() {
this.setState( {disabled: !this.state.disabled} )
}
render() {
return(
<div>
<input
className = "typing-container"
placeholder= " type here "
disabled = {(this.state.disabled)? "disabled" : ""}/>
<button onClick = {this.handleGameClik.bind(this)}> Start Game </button>
<button> Fetch Data </button>
</div>
);
}
};
Working Codepen here.
** 2019 **
Another option is to use, react-hooks' hook useState.
Edit: In a functional component
import React, {useState} from 'react';
function Typing(props) {
const [disabled, setDisabled] = useState(false);
function handleGameClick() {
setDisabled(!disabled);
}
return (
<div>
<input
className='typing-container'
placeholder=' type here '
disabled={disabled}
/>
<button type='submit' onClick={handleGameClick}> Start Game </button>
<button> Fetch Data </button>
</div>
);
}
This might confuse you, but the guys at React.js actually rebuild every form component and made them look almost exactly like the native HTML component. There are some differences however.
In HTML you should disable an input field like this:
<input disabled="disabled" />
But in React.js you'll have to use:
<input disabled={true} />
The accepted example works because anything not 0 is considered true. Therefor "disabled" is also interpreted as true.
const [disabled , setDisabled] = useState(true)
if(condition){
setDisabled(false)
}else{
setDisabled(true)
}
return
<TextField placeholder="Name" disabled={ disabled} />