getting material-ui TextField value onsubmit - javascript

I want to get the value of TextField input and render the message conditionally. I tried this one, its working but this one is functioning dynamically because I used onChange. I want to achieve the same but using onSubmit on <Button> Is there anyway to do that?
import React from 'react';
import { Component } from 'react';
import Button from '#mui/material/Button';
import { TextField } from '#mui/material';
class App extends Component
{
state = {
myValue: null,
}
handleChange = (e) => this.setState({
myValue: e.target.value
})
render() {
return (
<div>
<TextField
value={this.state.myValue}
onSubmit={this.handleChange}
/>
<button >Get Weather</button>
{this.state.myValue ? <p>value inputed </p>: <p>no input</p>}
</div>
)
}
}
export default App;

Using Refs is what you need. You can get the current value of your input by clicking a button and only then change the state.
Demo
import React, { createRef } from "react";
import { Component } from "react";
import { TextField } from "#mui/material";
class App extends Component {
constructor(props) {
super(props);
this.textInput = createRef();
this.state = {
myValue: ""
};
}
showRefContent = () => {
this.setState({
myValue: this.textInput.current.value
});
};
handleChange = (e) =>
this.setState({
myValue: e.target.value
});
render() {
return (
<div>
<TextField inputRef={this.textInput} />
<button onClick={this.showRefContent}>Get Weather</button>
<p>
{this.state.myValue.length > 0
? `text:${this.state.myValue}`
: "no text"}
</p>
</div>
);
}
}
export default App;

you just need to you onkeydown instead onsubmit.
<TextField
value={this.state.myValue}
onKeyDown={this.handleChange}
/>
or use
<form onSubmit={handleChange }>
<TextField
value={this.state.myValue}
onKeyDown={this.handleChange}
/>
<button type="submit">submit</button>
</form>

Related

Input tag onChange returning undefine value

I have been stuck on one issue to fetch the input text field from the input field. Essentially, I want to make a search function that gets the text and processes it further.
Please refer to the code for the information and returning div is at the bottom.
import React from 'react';
import ReactDOM from 'react-dom';
import { useState, useEffect } from 'react';
import { Input, InputGroup, Icon} from 'rsuite';
import { Button, IconButton, ButtonGroup, ButtonToolbar } from 'rsuite';
import './App.css';
import Search from './search.js';
// import default style
import 'rsuite/dist/styles/rsuite-default.css';
import { render } from 'react-dom';
const styles = {
marginBottom: 10
};
const center = {
padding: '25% 25% 25%'
}
class App extends React.Component {
constructor(props){
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.state = {
inputValue: 'Nothing'
}
}
handleInputChange(event){;
this.setState({inputValue: event.target.value});
};
render(){
return (
<div >
<div style={center} >
<InputGroup style={styles}> <Input size="md" value={this.inputValue} onChange={(e) => this.handleInputChange(e)} /><InputGroup.Addon>
<Button appearance="default"><Icon icon="search" /></Button>
</InputGroup.Addon>
</InputGroup>
</div>
</div>
)
}
}
export default App;
There's a ; in the start of your handleInputChange function.
Input from rsuite directly returns value onChange but you are referring to e.target.value.
And also the value should be this.state.inputValue
Here is the solution.
handleInputChange(value) {
console.log("values>>>>", value);
this.setState({ inputValue: value });
}
render() {
return (
<div>
<div style={center}>
<InputGroup style={styles}>
{" "}
<Input
size="md"
value={this.state.inputValue}
onChange={(e) => this.handleInputChange(e)}
/>
<InputGroup.Addon>
<Button appearance="default">
<Icon icon="search" />
</Button>
</InputGroup.Addon>
</InputGroup>
</div>
</div>
);
}
}
you can also refer to https://codesandbox.io/s/zen-field-njxn0?file=/src/App.js:590-1213
Your problem is very simple. You are setting value={this.inputValue} but you should use value={this.state.inputValue}. Because this.inputValue doesn't exist, your value gets set to undefined. Using value={this.state.inputValue} should fix your problem.

React: Toggle content in another component

I'm new to React and I'm stuck in this problem. I have a toggle component that is rendering a button to show/hide data aswell as the data that is being rendered.
I want to separate both the button and the data so I can display the content in another component, and being able to hide it and show it from the toggle component, if it makes sense.
Here is a picture to demonstrate what I'm wishing to do.
Toggle Example
The toggleComponent.js that contains the button and the data :
import React, { Component } from 'react';
export default class toggleComponent extends React.Component{
constructor(){
super();
this.state={
isShowBody: false
}
}
handleClick = (event) => {
this.setState({ isShowBody: !this.state.isShowBody })
}
checkbox = () => {
return (
<div >
<span className="switch switch-sm" >
<label>
<input type="checkbox" name="select" onClick={this.handleClick.bind(this)}/>
<span />
</label>
</span>
</div>
)
}
content = () => {
return (
<div>
Displaying text
</div>
)
}
render() {
return (
<div>
{this.checkbox()}
{this.state.isShowBody && this.content ()}
</div>
);
}
}
Just make another component named content.js. Import ContentComponent inside ToggleComponent and render it using flag.
Stackblitz Demo
Solution:
Toggle Component
import React, { Component } from "react";
import ContentComponent from "./content.js";
export default class toggleComponent extends React.Component {
constructor() {
super();
this.state = {
isShowBody: false
};
}
handleClick = event => {
this.setState({ isShowBody: !this.state.isShowBody });
};
checkbox = () => {
return (
<div>
<span className="switch switch-sm">
<label>
<input
type="checkbox"
name="select"
onClick={this.handleClick.bind(this)}
/>
<span />
</label>
</span>
</div>
);
};
render() {
return (
<div>
{this.checkbox()}
{this.state.isShowBody && <ContentComponent />}
</div>
);
}
}
Content Component
import React, { Component } from "react";
export default class ContentComponent extends React.Component {
content = () => {
return <div>Displaying text</div>;
};
render() {
return <div>{this.content()}</div>;
}
}

How do Is stop React App from resetting everything after submit form

I am trying to build a simple todo app but when I click submit on input for the form the page refreshes and all the data from the input is erased or lost, I am not sure.
console logs appear for a split second then they disappear after refresh. the array with list of todo seems to get filled with input but after refresh it disappears; or at least that is my understanding.
import React from "react"
import './App.css'
import TodoList from './components/TodoList.js'
class App extends React.Component {
state = {
count:0
}
increment = () => {
this.setState({
count: this.state.count + 1
})
}
decrement = () => {
this.setState({
count: this.state.count -1
})
}
render(){
return(
<div className="App">
<TodoList/>
</div>
)
}
}
export default App
import React from "react"
import TodoForm from "./TodoForm"
export default class TodoList extends React.Component {
state = {
todos: []
};
addTodo = (todo) => {
this.setState({
todos: [todo]
});
};
render() {
return (
<div>
<TodoForm onSubmit={this.addTodo}/>
{JSON.stringify(this.state.todos)}
</div>
);
}
}
import React from "react"
import shortid from "shortid"
class TodoForm extends React.Component {
state = {
text: ""
}
handleChange = (event) =>{
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit = (event) => {
event.preventDefualt()
this.props.onSubmit({
id: shortid.generate(),
text: this.state.text,
complete: false
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit} >
<input
name="text"
value={this.state.text}
placeholder="todo..."
onChange={this.handleChange}
/>
</form>
</div>
)
}
}
export default TodoForm
Submitting a form does a full page reload by default. To avoid this you should call event.preventDefault() in the onSubmit method.
In this case it looks like you have a typo in handleSubmit method. The line event.preventDefualt() should be event.preventDefault() (defualt vs default).
You have a typo in event.preventDefualt(). It should be event.preventDefault().

Redux form state is undefined

I'm using react-redux to access the state of a form from another component. This is how I export the form:
import _ from 'lodash';
import { reduxForm, Field } from 'redux-form';
import formFields from './formFields';
import OrderField from './OrderField';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
class OrderForm extends Component {
constructor(props) {
super(props);
this.renderFields = this.renderFields.bind(this);
}
renderFields() {
return _.map(formFields, ({ label, name }) => {
return (
<Field
key={name}
component={OrderField}
type="text"
label={label}
name={name}
/>
);
});
}
render() {
return (
<div>
<form onSubmit={this.props.handleSubmit(this.props.onOrderSubmit)}>
{this.renderFields()}
<button type="submit" className="waves-effect waves-light btn-large red darken-2 white-text">
Submit Order
<i className="material-icons right">done</i>
</button>
<p>Pay cash on delivery</p>
</form>
</div>
);
}
}
export default reduxForm({
form: 'orderForm'
})(OrderForm);
Also a container form:
import OrderForm from './OrderForm';
import React, { Component } from 'react';
import { reduxForm } from 'redux-form';
class OrderNew extends Component {
constructor(props) {
super(props);
this.submitOrder = this.submitOrder.bind(this);
}
submitOrder(values) {
console.log("handle submit order");
}
render() {
return (
<OrderForm
onOrderSubmit={ this.submitOrder }/>
);
}
}
export default reduxForm({
form: 'orderForm'
})(OrderNew);
and I'm trying to access the state.form.orderForm.values property like so in another component:
function mapStateToProps(state) {
console.log(state);
return {
cart_items: state.order.cart_items,
products: state.order.products,
total: state.order.total,
formValues: state.form.orderForm.values
};
}
But I get the error that state.form.orderForm.values is undefined. What am I doing wrong?
In fact, console.log(state.form) prints {} in mapStateToProps.

Get value of input text with react-bootstrap

I try to get value into a input text and add it to a text area with react-bootstrap.
I know I must use ReactDOM.findDOMNode to get value with ref. I don't understand what is wrong.
Here my code :
import React from 'react';
import logo from './logo.svg';
import ReactDOM from 'react-dom';
import { InputGroup, FormGroup, FormControl, Button} from 'react-bootstrap';
import './App.css';
class InputMessages extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.GetMessage= this.GetMessage.bind(this);
this.state = {message: ''};
}
handleChange(event)
{
this.setState({message: this.GetMessage.value});
}
GetMessage()
{
return ReactDOM.findDOMNode(this.refs.message );
}
render() {
var message = this.state.message;
return(
<FormGroup >
<FormControl
componentClass="textarea" value={message} />
<InputGroup>
<FormControl type="text" ref='message' />
<InputGroup.Button>
<Button bsStyle="primary" onClick={this.handleChange}>Send
</Button>
</InputGroup.Button>
</InputGroup>
</FormGroup>
);
}
}
export default InputMessages;
Form Control has a ref prop, which allows us to use React Refs
Sample Code :
class MyComponent extends React.Component {
constructor() {
/* 1. Initialize Ref */
this.textInput = React.createRef();
}
handleChange() {
/* 3. Get Ref Value here (or anywhere in the code!) */
const value = this.textInput.current.value;
}
render() {
/* 2. Attach Ref to FormControl component */
return (
<div>
<FormControl ref={this.textInput} type="text" onChange={() => this.handleChange()} />
</div>
)
}
}
Hope this helps!
Add an Input ref to your form :
<FormControl inputRef={ref => { this.myInput = ref; }} />
so now you get the value like
this.myInput.value

Categories

Resources