I want to show <div nameClass="showName"> when button is clicked and this.state.name's value is not null.
The showResult state check name's value is null or not, but this isn't work I guess.
I don't know how to fix it.
import React, { Component } from 'react';
class PhoneForm extends Component{
state = {
name : '',
showResults : false
}
handleChange = (e) => {
this.setState({
name: e.target.value
})
}
onClick=(e)=>{
this.setState({
showResults: this.state.name===null ? false : true
})
}
render(){
return (
<form>
<input
placeholder="name"
value={this.state.name}
onChange={this.handleChange}/>
<button onClick={this.onCkick}>클릭!</button>
<div nameClass="showName" style={{display:(this.state.showResults? 'block':'none')}}>{this.state.name}</div>
</form>
);
}}
export default PhoneForm;
You have a small typo in your render method. Your change event handler is called onClick, not onCkick.
You must also make sure to use preventDefault on the event when the form is submitted, or the browser will reload.
class PhoneForm extends React.Component {
state = {
name: "",
showResults: false
};
handleChange = e => {
this.setState({
name: e.target.value
});
};
onClick = e => {
e.preventDefault();
this.setState({
showResults: this.state.name === null ? false : true
});
};
render() {
return (
<form>
<input
placeholder="name"
value={this.state.name}
onChange={this.handleChange}
/>
<button onClick={this.onClick}>클릭!</button>
<div
nameClass="showName"
style={{ display: this.state.showResults ? "block" : "none" }}
>
{this.state.name}
</div>
</form>
);
}
}
ReactDOM.render(<PhoneForm />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
When the input is empty it will show nothing hence we don't need to check whether the input has a value or not.
What is needed to to toggle the visibility for on the onClick function.
Set the <button/> type attribute to 'button' if you dont want to refresh the page all the time.
like: <button type="button" onClick={this.onClick}>클릭!</button>
Or trigger the preventDefault() on the event.
class PhoneForm extends React.Component {
state = {
name: "",
showResults: true
};
handleChange = e => {
this.setState({
name: e.target.value,
showResults: true
});
};
onClick = e => {
this.setState({
showResults: !this.state.showResults
});
};
render() {
return (
<form>
<input
placeholder="name"
value={this.state.name}
onChange={this.handleChange}
/>
<button type="button" onClick={this.onClick}>클릭!</button>
<div
nameClass="showName"
style={{ display: this.state.showResults ? "block" : "none" }}
>
{this.state.name}
</div>
</form>
);
}
}
ReactDOM.render(<PhoneForm />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Related
I am completely new to React JS, I have no Idea how to do in ReactJS.
I have to hide the Submit button initially, when keyin to dates fields then Submit button should be display.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
<input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;
You can add check on base of start and end dates of your state.
Try following code
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { startdate: '', enddate: '' };
}
mySubmitHandler = (event) => {
event.preventDefault();
alert("You are submitting " + this.state.startdate +"and"+ this.state.enddate);
}
myChangeHandler = (event) => {
this.setState({startdate: event.target.value});
}
myEndDate = (event) => {
this.setState({enddate: event.target.value});
}
render() {
return (
<form onSubmit={this.mySubmitHandler}>
<img src="C:\\Users\\A9002255\\Desktop\is.jpg"></img>
<h2>Please select the Date range of .CSV </h2>
<input
type='date'
onChange={this.myChangeHandler}
/>
<span> </span>
<input
type="date"
onChange={this.myEndDate}
/>
<div>
{this.state.startdate && this.state.enddate && <input
type='submit' value="Download" class="bi bi-cloud-arrow-down" style={{ width: '10%', height: 30}}
/>}
</div>
</form>
);
}
}
ReactDOM.render(<MyForm />, document.getElementById('root'));
export default MyForm;
I am trying to go to the URL, which is declared in the input field, when I click on the button. I am totally new to React, so any help would be appreciated!
This is the current Component:
class MyComponent extends React.Component {
render(){
return (
<form>
<input type="text" name="code" placeholder="http://www.google.de" />
<input type="button" value="Go" />
</form>
)
}
}
Making you input fully controlled should do the trick. Explanation in code comments
class MyComponent extends React.Component {
state = {
code: '' // initial value
}
// save code in state on change
setCode = e => this.setState({code: e.target.value})
// change href to be this.state.code value
go = e => {
e.preventDefault()
window.location.href = this.state.code
}
render(){
return (
<form>
{/* make input fully controlled */}
<input type="text" name="code" value={this.state.code} onChange={this.setCode} placeholder="http://www.google.de" />
{/* handle button click event*/}
<input type="button" value={`Go to ${this.state.code}`} onClick={this.go}/>
</form>
)
}
}
ReactDOM.render(<MyComponent/>, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" />
Following is solution by using refs:-
class App extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
submitHandler = () => {
let value = this.inputRef.current.value;
console.log(value);
if (value !== "") window.location.href = value;
};
render() {
return (
<form onSubmit={() => this.submitHandler()}>
<input
ref={this.inputRef}
type="text"
name="code"
placeholder="http://www.google.de"
/>
<input type="submit" value="Go" />
</form>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root' />
How would I go about preventing someone from adding nothing my to do list?
AppTodo.JS
import React, { Component } from "react";
import PropTypes from "prop-types";
export class AddTodo extends Component {
state = {
title: ""
};
onSubmit = e => {
e.preventDefault();
if (this.state.addTodo === "") {
alert("??");
} else {
this.props.addTodo(this.state.title);
this.setState({ title: "" });
}
};
onChange = e => this.setState({ title: e.target.value });
render() {
return (
<form onSubmit={this.onSubmit} stlye={{ display: "flex" }}>
<input
type="text"
name="title"
style={{ flex: "10", padding: "5px" }}
placeholder="Add Things Todo..."
value={this.state.title}
onChange={this.onChange}
/>
<input
type="submit"
value="Submit"
className="btn"
style={{ flex: "1" }}
/>
</form>
);
}
}
// Prop Types
AddTodo.propTypes = {
addTodo: PropTypes.func.isRequired
};
export default AddTodo;
I am new to React, just doing it for fun and spent a few hours trying to make conditionals work within the onSumbit method and even in the render() method, but can't seem to make anything work.
Thanks ahead of time.
You do not have an addTodo variable in your state, but you do have a title variable.
Change this.state.addTodo === "" to this.state.title === "" and it will work as expected.
class AddTodo extends React.Component {
state = {
title: ""
};
onSubmit = e => {
e.preventDefault();
if (this.state.title === "") {
alert("??");
} else {
this.props.addTodo(this.state.title);
this.setState({ title: "" });
}
};
onChange = e => this.setState({ title: e.target.value });
render() {
return (
<form onSubmit={this.onSubmit} stlye={{ display: "flex" }}>
<input
type="text"
name="title"
style={{ flex: "10", padding: "5px" }}
placeholder="Add Things Todo..."
value={this.state.title}
onChange={this.onChange}
/>
<input
type="submit"
value="Submit"
className="btn"
style={{ flex: "1" }}
/>
</form>
);
}
}
ReactDOM.render(
<AddTodo addTodo={todo => console.log(`Added todo: ${todo}`)} />,
document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I have been trying to toggle state using dynamic key value pairs but it doesn't seem to happen.
Here is the state:
constructor(props) {
super(props);
this.state = {
firecrackerAnimation: false,
mainImageBounceAnimation: false,
flowersFallingAnimation: false,
};
}
This is the code I am using to toggle state
changeAnimation = e => {
this.setState(
{
[e.target.value]: !(this.state[event.target.value]),
},
() => {
console.log(this.state);
}
);
Below is where I am using it inside my render()
<div className="form-row">
<span className="form-label">Animations</span>
<input
className=""
type="checkbox"
value="firecrackerAnimation"
onClick={this.changeAnimation}
checked={this.state.firecrackerAnimation}
/>{" "}
Fire Cracker Animation <br />
<input
className=""
type="checkbox"
value="mainImageBounceAnimation"
onChange={this.changeAnimation}
checked={this.state.mainImageBounceAnimation}
/>{" "}
Main Image Bounce <br />
<input
className=""
type="checkbox"
value="flowersFallingAnimation"
onChange={this.changeAnimation}
checked={this.state.flowersFallingAnimation}
/>{" "}
Flowers Falling Animation <br />
</div>
There are several mistakes I've pointed out:
You should use e.target.name in order to get the name of the checkbox being clicked.
You have to provide name for checkboxes, not the value
WORKING DEMO
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
firecrackerAnimation: false,
mainImageBounceAnimation: false,
flowersFallingAnimation: false,
};
}
changeAnimation = (e) => {
this.setState(
{
[e.target.name]: !(this.state[e.target.name]),
},
() => {
console.log(this.state);
})
}
render() {
return (
<div className="form-row">
<span className="form-label">Animations</span>
<input
className=""
type="checkbox"
name="firecrackerAnimation"
onChange={this.changeAnimation}
checked={this.state.firecrackerAnimation}
/>{" "}
Fire Cracker Animation <br />
<input
className=""
type="checkbox"
name="mainImageBounceAnimation"
onChange={this.changeAnimation}
checked={this.state.mainImageBounceAnimation}
/>{" "}
Main Image Bounce <br />
<input
className=""
type="checkbox"
name="flowersFallingAnimation"
onChange={this.changeAnimation}
checked={this.state.flowersFallingAnimation}
/>{" "}
Flowers Falling Animation <br />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
.as-console-wrapper { max-height: 50% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Change your changeAnimation function as follows:
changeAnimation(e){
var value = e.target.value;
this.setState({[value]: !(this.state[value])});
}
Here is the fiddle.
you have problem with your change animation event
changeAnimation = e => {
this.setState(
{
// [e.target.value]: !(this.state[event.target.value]),
//here you have to change like
this.state[e.target.value]: !(this.state[event.target.value]),
},
() => {
console.log(this.state);
}
);
The other responses are correct in that you can setState with dynamic keys and variables, however React recommends against using state inside setState.
From the docs:
"React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state."
- https://reactjs.org/docs/state-and-lifecycle.html
You can take the same idea as the other comments mention and make setState accept a function instead. I used this in my code (button was defined in an outer function).
this.setState((prevState) => ({
[button]: !prevState[button]
}));
How to get the text field value and push that value to an arrayList in react js?
I want to get the value from the text box and push it to Modules array so that i can render the values by iterating it.
I tried to use ref but getting error.
Can you help me?
constructor(props) {
super(props);
this.state={
module:'',
Modules: []
}
}
change (event){
this.setState({
[event.target.name]:event.target.value
});
};
createModule (e) {
e.preventDefault();
console.log("submitted",this.state.module);
this.setState(previousState => ({
...state,
thisModules: [...previousState.Modules, 'new value']
}));
};
render(){
return(
<form className="form-inline">
<div className="form-group">
Module Name:
<input type="text" id="module"
name="module"
placeholder="module"
className="form-control"
ref="Module"
value ={this.state.module}
onChange={event => this.change(event)}/>
<button type="submit" className="btn btn-primary" onClick={(event) => this.createModule(event)}>Add Module</button>
</div>
</form>
mylist.push(document.getElementById('textbox_id').value)
with mylist as your list and textbox_id as the id of the textbox should work.
Consider this is plain javascript as I don't really see any difference with react.
The main problem from running your code was that in createModule you weren't putting this in front of state. If you'd given details of the error this would have helped.
There were a few other typos, and a work solution is below.
class ModuleList extends React.Component {
constructor(props) {
super(props);
this.state={
module:'',
Modules: []
}
}
change (event){
this.setState({
[event.target.name]:event.target.value
});
}
createModule (e) {
e.preventDefault();
console.log("submitted",this.state.module);
this.setState(previousState => ({
...this.state,
Modules: [...previousState.Modules, this.state.module]
}));
};
render(){
return (
<form className="form-inline">
<div className="form-group">
Module Name:
<input type="text" id="module"
name="module"
placeholder="module"
className="form-control"
ref="Module"
value={this.state.module}
onChange={event => this.change(event)}/>
<button type="submit" className="btn btn-primary" onClick={(event) => this.createModule(event)}>Add Module</button>
</div>
<ul>
{
this.state.Modules.map(
(m) => <li>{m}</li>
)
}
</ul>
</form>
);
}
}
ReactDOM.render(
<ModuleList />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<p>My App:</p>
<div id='root' />