Submit value as object - javascript

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

Related

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>

React Input text now being shown

I'm trying to create a composed input text (joining 4 input components) but i'm not being able.
Everything seems to be OK and the only way I Have been able to show the input text is placing it in the render of the main React component (cardform). In the DOM explorer (chrome) the only componet I an empty cardNumberFullField
This is the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/react#15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel" src="script.js"></script>
</body>
</html>
This is the JS:
class CardForm extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<cardNumberFullField />
</div>
)
}
}
function cardNumberFullField() {
return (
<div>
<cardNumberInputField inputName="0" />
<cardNumberInputField inputName="1" />
<cardNumberInputField inputName="2" />
<cardNumberInputField inputName="3" />
</div>
)
}
function cardNumberInputField(props) {
return (
<div>
<input id={props.inputName} name={props.inputName} type="text" />
</div>
)
}
// Main render
ReactDOM.render(<CardForm />, document.getElementById("root"))
React custom components always needs to be in Capitalized. So cardNumberFullField should be CardNumberFullField, cardNumberInputField should be CardNumberInputField
Check Specifying The React Element Type.
The first part of a JSX tag determines the type of the React element.
Capitalized types indicate that the JSX tag is referring to a React
component. These tags get compiled into a direct reference to the
named variable, so if you use the JSX expression, Foo must be
in scope.
class CardForm extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<CardNumberFullField />
</div>
);
}
}
function CardNumberFullField() {
return (
<div>
<CardNumberInputField inputName="0" />
<CardNumberInputField inputName="1" />
<CardNumberInputField inputName="2" />
<CardNumberInputField inputName="3" />
</div>
);
}
function CardNumberInputField(props) {
return (
<div>
<input id={props.inputName} name={props.inputName} type="text" />
</div>
);
}
// Main render
ReactDOM.render(<CardForm />, 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>

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

How do i execute alert() in parent component after onClick in child component

In here, i'm passing data from child to parent and i am able to pass it through but i want alert function to execute only after onClick event is triggered in the child component but it is executing everytime onSubmit event is fired, it looks like there is a requirement of some life cycle method in order to make it work but i'm not getting it. Can someone help me with this please
Parent
onList(list) {
alert(list);
}
render() {
return (
<div>
<form>
<input type='textarea'
onKeyPress={this.handleSubmit}
/>
<Child {...this.state} sendList={this.onList}/>
</form>
</div>
)
}
Child
{
this.props.listArr.map((list,index) => {
return(
<div key={index}>
<li>{list}
<div>
<button className="btn btn-primary btn-xs glyphicon glyphicon-pencil" onClick={this.props.sendList(list)} />
</div>
</li>
</div>
)})
}
change to:
<Child {...this.state} sendList={(...args) => this.onList(...args)} />, to preserve the function context.
then, in Child just call that method as this.props.sendList()
You can use event.preventDefault() on button click so the form doesn't get submitted.
const Child = ({ sendList, list }) =>
<div>
<button onClick={(event) => sendList(event, list)}>Click</button>
</div>
class Parent extends React.Component {
constructor() {
super()
this.onList = this.onList.bind(this)
}
onList(event, list) {
event.preventDefault()
console.log('onList', list)
}
render() {
return (
<form>
<Child sendList={this.onList} list={[]} />
</form>
)
}
}
ReactDOM.render(
<Parent />,
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>

reactjs parent trigger child component

I have a parent component, which is basically a Form.
export default class Parent extends Component{
submitInput(event){
...call Children
}
render(){
return(
<div>
<form className="form-horizontal" onSubmit= {this.submitInput.bind(this)}>
{this.props.children}
<button type="submit">Submit</button>
</div>
</form>
</div>);
}}
The children can be different types of inputs all with a common function called validate().
Here is one example of a child
export default class Child extends Component{
validate(){
..validate stuff
}
render(){
return(
<div className="form-group">
<textarea ref={this.props.name} />
</div>
);
}
}
On Submission of the parent Component I want validate all Child inputs using their validate() function.
How can I do that?
Thanks in advance
Clone the entire children with new ref prop using React.cloneElement. On submit use the refs to access the child's methods.
See the example below. If more elaboration needed, please comment.
Hope this helps!
class Form extends React.Component{
submitInput(){
this.childrenClone.forEach((el) => {
var r = el.ref //use the ref to access the child's methods
this.refs[r].validate()
})
}
render() {
this.childrenClone = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
ref: Math.random().toString(36).slice(-5) //add a random string as a ref
})
)
return <div>
<form className="form-horizontal" onSubmit={this.submitInput.bind(this)}>
{this.childrenClone}
<button type="submit">Submit</button>
</form>
</div>
}
}
class Child extends React.Component{
validate(){
console.log('validate textarea') //on validate log this
}
render() {
return <div className="form-group">
<textarea />
</div>
}
}
class ChildInput extends React.Component{
validate(){
console.log('validate Input') //on validate log this
}
render() {
return <div className="form-group">
<input type="text" />
</div>
}
}
class Parent extends React.Component{
render(){
return <Form>
<Child/>
<Child/>
<ChildInput/>
<ChildInput/>
</Form>
}
}
ReactDOM.render(<Parent/>, document.getElementById('app'))
<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"></div>

Categories

Resources