onClick vs onSubmit in React - javascript

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...

Related

Submit form on checkbox change and keep built-in browser validation

My form consists of text input and a checkbox.
The text input cannot be empty upon form submit, hence the required parameter.
I want to submit the form on each checkbox change and still keep this built-in validation. Currently, if the text input is empty and I click the checkbox, it WILL submit.
How can keep the validation on checkbox change?
const Form = () => {
const handleSubmit = (e: any) => {
e.preventDefault()
alert('submitted')
}
return (
<form onSubmit={handleSubmit}>
<input type="text" required />
<input type="checkbox" onChange={(e) => handleSubmit(e)} />
<button type="submit">Submit</button>
</form>
)
}
const root = document.getElementById('root')
ReactDOM.render(<Form />, 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>
You can try to trigger the submit button, in this case the html5 validation should run:
const Form = () => {
const handleSubmit = (e: any) => {
e.preventDefault()
alert('submitted')
}
const handleChange = (e: any) => {
const btn = document.getElementById('btnSubmit');
btn.click();
}
return (
<form onSubmit={handleSubmit}>
<input type="text" required />
<input type="checkbox" onChange={(e) => handleChange(e)} />
<button id="btnSubmit" type="submit">Submit</button>
</form>
)
}
const root = document.getElementById('root')
ReactDOM.render(<Form />, 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>

Input reset in react

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>

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>
)
);
};

Submit value as object

<div>
Player One <input ref="p1Name"/>
Player Two <input ref="p2Name"/>
<button onClick={() => this.submit(this.refs.p1Name.value, this.refs.p2Name.value)}>submit result</button>
</div>
This code submits as expected. but i want to submit it as on object. i have tried wrapping the arguments in {} but it then complains about the this keyword. how can i submit it so the function receives it as an object?
This is what I have tried:
<button onClick={() => this.submit({this.refs.p1Name.value, this.refs.p2Name.value})}>submit result</button>
You can wrap them in an object like this:
this.submit({a: this.refs.p1Name.value, b: this.refs.p2Name.value})}
A working example:
class App extends React.Component {
constructor(props) {
super(props);
this.submit = this.submit.bind(this);
}
submit(params) {
console.log(params);
}
render() {
return (
<div>
Player One <input ref="p1Name" />
Player Two <input ref="p2Name" />
<button
onClick={() =>
this.submit({a: this.refs.p1Name.value, b: this.refs.p2Name.value})}
>
submit result
</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>
<div id="root"></div>

Open "choose file" dialog box on onclick of Raised Button Material ui

I have a Floating button (material ui) in my react project. I want to open "choose file" dialoge box whenever I click it. I am not getting any solution to do that. I tried doing this but didn't work. and I don't want to use jquery.
</div>
<input id="myInput" type="file" style="visibility:hidden" />
<FloatingActionButton className="floatingButton" backgroundColor='#293C8E' onClick ="$('#myInput').click();">
<ContentAdd />
</FloatingActionButton>
</div>
Can someone please tell me what exactly I need to do?
Basic example (does not include what to do with selected file):
<div>
<input id="myInput" type="file" ref={(ref) => this.upload = ref} style={{ display: 'none' }} />
<FloatingActionButton
className="floatingButton"
backgroundColor='#293C8E'
onClick={(e) => this.upload.click() }
>
<ContentAdd />
</FloatingActionButton>
</div>
So, your FloatingActionButton's onClick handler manually fires the click() handler of a hidden file upload control (input type="file"). A reference to the hidden upload control is obtained by putting a ref callback on it and storing that reference in "this.upload" (could also use DOM or jQuery to do that, but ref is preferred in React)
here is a working jsFiddle: https://jsfiddle.net/432yz8qg/58/
You can do the trick with the help of <label/> tag:
<label htmlFor='myInput'>
<input id="myInput" type="file" style={{visibility: 'hidden'}} />
<FloatingActionButton
className="floatingButton"
backgroundColor='#293C8E'
>
<ContentAdd />
</FloatingActionButton>
</label>
I solved this problem in a more React way than Jeff solution though my solution imply the use of multiple CSS rules.
I used a FlatButton with the props containerElement set to "label" :
const { FlatButton, SvgIcon, MuiThemeProvider, getMuiTheme } = MaterialUI;
class Example extends React.Component {
render() {
const buttonStyle = {
minWidth: '56px',
width: '56px',
minHeight: '56px',
height: '56px',
borderRadius: '28px',
};
return (
<div>
<FlatButton
containerElement="label"
backgroundColor='#293C8E'
style={buttonStyle}
>
<input type="file" style={{ display: 'none' }} />
</FlatButton>
</div>
);
}
}
const App = () => (
<MuiThemeProvider muiTheme={getMuiTheme() }>
<Example />
</MuiThemeProvider>
);
ReactDOM.render(
<App />,
document.getElementById('container')
);
<script src="https://unpkg.com/react#15.2.1/dist/react-with-addons.js"></script>
<script src="https://unpkg.com/react-dom#15.2.1/dist/react-dom.js"></script>
<script src="https://rawgit.com/nathanmarks/3f5196f5973e3ff7807f2bab4e603a37/raw/f409f3bf5902c211b358a3ebe7b6cd366da551e8/mui-umd.js"></script>
<div id="container"></div>
More details here : https://stackoverflow.com/a/36262984/2590861

Categories

Resources