Input reset in react - javascript

I am working on a react app. Where I am talking a two inputs in form after submitting the form my fields are not reseting. How to do those. I am attaching my form component code can anyone help me out with this.
import React, { Component } from 'react';
class Form extends Component {
render() {
return (
<form onSubmit={this.props.getWeather}>
<input type="text" name="city" placeholder="city.." />
<input type="text" name="country" placeholder="country.." /><br></br>
<button >Submit</button>
</form>
);
}
}
export default Form;

Inside the getWeather method you will have access the React synthetic event object, say event. Get the native dom element out of it using event.target, and then call the reset() method as event.target.reset(). This will clear all the form input values.
Play with the below example.
function App() {
const onFormSubmit = e => {
e.preventDefault();
e.target.reset();
};
return (
<div className="App">
<form onSubmit={onFormSubmit}>
<div>
<label htmlFor="name">Enter your name: </label>
<input type="text" name="name" id="name" required />
</div>
<div>
<input type="submit" value="Reset!" />
</div>
</form>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<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

How to call a function in a function based ReactJS component?

In ReactJS would like to have a component from a function, and send a call to a function when a form is posted.
This example doesn't work. How can be fixed?
import React from 'react';
import Link from "react-router-dom/Link";
function AddPhoto(props) {
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
<form className="form" onSubmit={e => this.handleSubmit(e)}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
export function handleSubmit(event) {
console.log("Form has been submitted");
console.log(event.target.element.link.value);
}
I think there are several issues with your code.
You probably want to export your AddPhoto component instead of your handleSubmit function. Assuming that your file is only exporting your AddPhoto component, you don't have to declare a constant and you can straightaway export default your AddPhoto function.
I actually don't see the reason to export your handleSubmit function. So I will include that function inside your AddPhoto component.
There is a - in your this.handleSubmit function, also functional component don't have to use this, furthermore your handleSubmit function is not within your functional component's scope. So it won't work.
You probably don't need the . in your input className props as well.
I've formatted your code to make it look cleaner :)
Here are the codes for you to refer.
const AddPhoto = (props) => {
const handleSubmit = (event) => {
// Add this if you want to prevent the page from reloading and updating your url
event.preventDefault();
console.log("Form has been submitted");
// Assuming you want to get the `link` field's value, you can get it by using this
console.log(event.target.link.value);
}
return (
<div>
<h1>Pickture</h1>
<Link className="cancelIcon" to="/">
{" "}
</Link>
<div>
<form className="form" onSubmit={handleSubmit}>
<input
className="form input"
type="text"
placeholder="Link"
name="link"
/>
<input
className="form input"
type="text"
placeholder="Description"
name="description"
/>
<button type="submit">post</button>
</form>
</div>
</div>
);
}
export default AddPhoto;
Remove this from your handleSubmit since it's declared outside.
Remove export if you're declaring the function in the same file. Otherwise, you would have to define your function in a separate file and then import from there.
function AddPhoto(props) {
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
{/* Removed this.*/}
<form className="form" onSubmit={e => handleSubmit(e)}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
// Removed export
function handleSubmit(event) {
console.log("Form has been submitted");
console.log(event.target.element.link.value);
}
There are quite some issue with your code:
The button doesn’t have a type=“submit” on it, so therefor it won’t even submit the form when pressed.
HandleSubmit is an function specific to AddPhoto, so it should be inside the AddPhoto component. (I also like to use an arrow function in this case because it should be an anonymous function).
There is no need the use this because first of all this keyword is only used in classes to bind functions to the class. So because AddPhoto is an functional component, you don’t have to bind the function to the class.
You should add event.preventDefault();, because otherwise the page will reload (to submit the form) and you will lose your state of your application.
import React from 'react';
import Link from 'react-router-dom/Link';
export default function AddPhoto() {
const handleSubmit = event => {
event.preventDefault();
const link = event.target.link;
const description = event.target.description;
console.log('Form has been submitted');
};
return (
<div>
<h1>Picture</h1>
<Link className="cancelIcon" to="/">
cancel
</Link>
<div>
<form className="form" onSubmit={handleSubmit}>
<input
className="form-input"
type="text"
placeholder="Link"
name="link"
ref={linkInput}
/>
<input
className="form-input"
type="text"
placeholder="Description"
name="description"
ref={descriptionInput}
/>
<button type="submit">post</button>
</form>
</div>
</div>
);
}
Try this:
import React from 'react';
import Link from "react-router-dom/Link";
export function AddPhoto(props) {
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
<form className="form" onSubmit={handleSubmit}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
function handleSubmit(event) {
console.log("Form has been submitted");
console.log(event.target.element.link.value);
}
I think you should be needing to write something like ...
import React from 'react';
import Link from "react-router-dom/Link";
export const AddPhoto = props => {
const handleSubmit = e =>{
return(
console.log("Form has been submitted");
console.log(e.target.element.link.value);
)
}
return (<div>
<h1>Pickture</h1>
<Link className='cancelIcon' to="/"> </Link>
<div>
<form className="form" onSubmit={e => handleSubmit(e)}>
<input className='.form input' type='text' placeholder='Link' name='link'/>
<input className='.form input' type='text' placeholder='Description' name='description'/>
<button> post</button>
</form>
</div>
</div>)
}
AddPhoto.defaultProps = {
onSubmit: ()=>{}
}

How to totally disable a react component?

I have a react component which has some buttons and text inputs. I want to totally disable all the things inside this component until some other works are complete. How to make the entire inner component disabled?
You can add disabled props and use CSS to disable div
const MyComponent = ({disabled}) => {
return (
<div style={disabled ? {pointerEvents: "none", opacity: "0.4"} : {}}>
<h1> Text</h1>
<input type="text"/>
<input type="password"/>
<button>Login</button>
</div>
)
}
Better to use form and fieldset, and put all the input/button elements inside that. You can disable all of them by setting the property disabled to fieldset.
Refer MDN Doc for more details.
Working example:
class App extends React.Component {
constructor () {
super()
this.state = { disable: false }
}
toggleDisable = () => this.setState(prevState => ({disable: !prevState.disable}))
buttonClick = (e) => {
e.preventDefault();
console.log('button clicked');
}
render (){
return (
<div>
<button className='toggle' onClick={this.toggleDisable}>Toggle Disable</button>
<form>
<fieldset disabled={this.state.disable}>
<input />
<button onClick={this.buttonClick}>Button</button>
</fieldset>
</form>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'))
.toggle {
margin-bottom: 20px;
}
<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='app' />
All you need to do is add a disabled prop on the component and pass it on to the inner fields like
<MyComponent disabled={shouldComponentBeDisabled} {...otherProps} />
and in implementation
const MyComponent = ({disabled}) => {
return <div>
<button disabled={disabled}>someBtn</button>
<input type="text" disabled={disabled}/>
</div>
}
You can use disabled prop pattern to save the day.
const App = () => {
return (
<div>
<SomeComponent disabled />
</div>
);
};
const SomeComponent = ({ disabled = false }) => {
return (
!disabled && (
<div>
<h2>Disable SomeComponent to see magic happen!</h2>
</div>
)
);
};

Need ref to <input> from semantic-ui-react's Form.Input - which is surrounded by divs in React

I am using semantic-ui-react's Form.Input, which wraps the input in two divs.
This means,
<Form.Input type='password' name='password' id='loginPassword'></Form.Input>
is rendered as follows:
<div class='field'>
<div class='ui fluid action left icon input'>
<input type='password' name='password' id='loginPassword' ...>
<button ...>
</div>
</div>
I would like to get the ref for the <input/> element, so that I can call focus().
My ref is set to the component when using ref='myRef'
ReactDOM.findDOMNode returns a DOM ref, but the ref is set to the outer div (with class='field').
How do I get a ref to the <input/> element?
BTW, I am using redux, although I don't think that matters
Form.Input is just a shorthand for some components that are wrapping an Input.
So behind the scenes this:
<Form.Input label='Enter Password' type='password' />
Is the same as this:
<Form.Field>
<label>Enter Password</label>
<Input type='password' />
</Form.Field>
semantic-ui-react supports the react ref API for Input, but make sure you are using the current ref API and not the old one:
<Input ref={ref => this.input = ref} />
running example:
const { Input, Button } = semanticUIReact; // import
class App extends React.Component {
onClick = () => this.input.focus();
render() {
return (
<div>
<Input ref={ref => this.input = ref} />
<Button onClick={this.onClick}>Focus</Button>
</div>
);
}
}
ReactDOM.render(<App />, 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>
<script src="https://cdn.jsdelivr.net/npm/semantic-ui-react#0.78.3/dist/umd/semantic-ui-react.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.min.css"/>
<div id="root"></div>
As you're using findDOMnode (usually not advised), you're back into standard js, so this :
ReactDOM.findDOMNode(your ref).querySelector('input')
should work

onClick vs onSubmit in React

I have a simple input in react that won't work with onSubmit but with onClick. Why is that? Here is the link to an example.
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center',
};
const clicked = e => {
alert("Hi")
}
const App = () => (
<div style={styles}>
<input type='submit' value='click' onSubmit={clicked}/>
</div>
);
ReactDOM.render(<App />, 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" />
onSubmit is a prop for <form>, you should add the handler on to that element:
<form onSubmit={onSubmit}>
<input ... />
</form>
I think it needs to be in a <form></form> for submit to work
Because you're not submitting anything. onSubmit is for submitting forms...

Passing react text field input values as parameters to a method

I have the below input fields of which I need to get the entered inputs and pass it to the onClick event of the button shown below.
<input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/>
<input type="text" style = {textFieldStyle} name="payloadBox" placeholder="Enter payload here..."/>
<button value="Send" style={ buttonStyle } onClick={this.publish.bind(this,<value of input field 1>,<value of input field2>)}>Publish</button><span/>
I have a method called publish which takes two string arguments. In place of those strings, I need to pass the values entered in the input fields. How can I achieve this without storing the values in states? I do not want to store the input field values in state variables. Any help would be much appreciated.
How can I achieve this without storing the values in states?
I think in this case better use states
class App extends React.Component {
constructor() {
super();
this.state = {
topicBox: null,
payloadBox: null
};
this.publish = this.publish.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
this.setState({
[target.name]: target.value
});
}
publish() {
console.log( this.state.topicBox, this.state.payloadBox );
}
render() {
return <div>
<input
type="text"
name="topicBox"
placeholder="Enter topic here..."
value={ this.state.topicBox }
onChange={ this.handleChange }
/>
<input
type="text"
name="payloadBox"
placeholder="Enter payload here..."
value={ this.state.payloadBox }
onChange={ this.handleChange }
/>
<button value="Send" onClick={ this.publish }>Publish</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<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="container"></div>
You can add ref for each text field, and read the value from it like:
class App extends React.Component {
constructor() {
super();
this.publish = this.publish.bind(this);
}
publish(topicBox, payloadBox) {
alert(this.refs.topic.value);
alert(this.refs.payload.value);
}
render() {
return <div>
<input
ref="topic"
type="text"
name="topicBox"
placeholder="Enter topic here..."/>
<input
ref="payload"
type="text"
name="payloadBox"
placeholder="Enter payload here..."/>
<button
value="Send"
onClick={this.publish}>
Publish
</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
Working fiddle https://jsfiddle.net/hjx3ug8a/15/
Thanks for Alexander T for his addition!

Categories

Resources