How to clear the materialUI textfield value in react?
Check the below code -
<TextField
hintText=""
ref={(node) => this._toField = node}
onChange={this.changeToText}
floatingLabelText="To*"
floatingLabelFixed={true}
fullWidth={true}
/>
I'm using the raisedButton while pressing it validate the above field. If the field has error then displaying the error message. If not, then we need to clear the input. But how can we clear the input text?
if you are using a stateless functional component then you can use react hooks.
Also make sure you are using inputRef
import React, { useState, useRef } from "react";
let MyFunctional = props => {
let textInput = useRef(null);
return (
<div>
<Button
onClick={() => {
setTimeout(() => {
textInput.current.value = "";
}, 100);
}}
>
Focus TextField
</Button>
<TextField
fullWidth
required
inputRef={textInput}
name="firstName"
type="text"
placeholder="Enter Your First Name"
label="First Name"
/>
</div>
);
};
There is a value property that you have to pass to the TextField component.
check example below:
class SomeComponent extends Component {
state = {value: ''}
resetValue = () => {
this.setState({value: ''});
}
render() {
return (
<div>
<TextField
...
value={this.state.value}
/>
<button onClick={this.resetValue}>Reset</button>
</div>
)
}
}
try this
import { Button, Container, InputBase } from '#material-ui/core'
import React, { useState } from 'react'
const ClearText = ()=> {
const [text , setText] = useState("")
const clearTextField = () => setText("")
return (
<Container>
<InputBase
value={text ? text : ""}
onChange={(e)=>setText(e.target.value)}
/>
<Button onClick={clearTextField} > Clear </Button>
</Container>
)
};
export default ClearText;
You need to, somehow, store the input's value. State seems to be an initial approach in this case. Whenever the text changes, you have to update the state. Same applies when you click the button and click the input's value afterwards:
class App extends React.Component {
constructor() {
super()
this.state = {
value: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleClick = this.handleClick.bind(this)
}
handleChange(event) {
this.setState({ value: event.target.value })
}
handleClick() {
// validation...
this.setState({ value: '' })
}
render() {
return (
<div>
<input type="text" value={this.state.value} onChange={this.handleChange}/>
<button onClick={this.handleClick}>Click-me</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
I am new to React and struggle to transform this function component into a class component with a constructor(). I can't figure out how to transform the functions happening onSubmit and onClick.
Thank you very much.
The function component:
import React, { useState, Component } from 'react';
import { render } from 'react-dom';
import './Options.css';
const Test = (props) => {
const [links, setLinks] = useState([]);
const [link, setLink] = useState('');
function handleSubmit(e) {
e.preventDefault();
const newLink = {
id: new Date().getTime(),
text: link,
};
setLinks([...links].concat(newLink));
setLink('');
}
function deleteLink(id) {
const updatedLinks = [...links].filter((link) => link.id !== id);
setLinks(updatedLinks);
}
return (
<div className="OptionsContainer">
<form onSubmit={handleSubmit}>
<input
type="text"
onChange={(e) => setLink(e.target.value)}
value={link}
/>
<button type="submit"> + </button>
</form>
{links.map((link) => (
<div key={link.id}>
<div>{link.text}</div>
<button onClick={() => deleteLink(link.id)}>Remove</button>
</div>
))}
</div>
);
};
export default Test;
When we work with class components a couple of things got changed, we have a new object this.state, a new function this.setState, you have to bind your functions on the constructor if you want to have access to this inside it. I think you'll learn way more if you read the code, so here this is your component as a class component:
import React, { Component } from 'react';
import './Options.css';
class App extends Component {
constructor() {
super()
this.state = {
links: [],
link: '',
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const newLink = {
id: new Date().getTime(),
text: this.state.link,
};
this.setState({links: [...this.state.links, newLink], link: ''});
}
deleteLink(id) {
const updatedLinks = [...this.state.links].filter((link) => link.id !== id);
this.setState({...this.state, links: updatedLinks });
}
render() {
console.log(this.state)
return (
<div className="OptionsContainer">
<form onSubmit={this.handleSubmit}>
<input
type="text"
onChange={(e) => this.setState({ ...this.state, link: e.target.value})}
value={this.state.link}
/>
<button type="submit"> + </button>
</form>
{this.state.links.map((link, index) => (
<div key={link.id}>
<span>{link.text}</span>
<button onClick={() => this.deleteLink(link.id)}>Remove</button>
</div>
))}
</div>
);
}
};
export default Test;
Without seeing your original functional component, it's going to be hard to tell you what the class component should look like.
To answer your question about why onSubmit might not be working, it's because onSubmit is expecting to be passed an uncalled function, so that the <form> element can call that function itself when the time is right.
You are currently calling the function this.handleOnSubmit(), which returns nothing, so no handler for the form submit is properly assigned. Try removing the call to the function, like this:
<form onSubmit={this.handleSubmit}>
I am building a To-Do List web app with React as my first project.
I want to implement local storage which works fine only that,I am unable to handle check and uncheck of the checkbox prefectly.
Here is a link to the deployed website so you can understand the problem I am having.
https://rapture-todo.netlify.app/
When you add a todo, and mark it complete.
on reload, the checkbox of the todo is unchecked but the todo is marked complete.
Here is my source code[github link- https://github.com/coolpythoncodes/React-ToDo-List].
For App.js
import React, { Component } from 'react';
import Header from './component/Header';
import Info from './component/Info';
import AddToDo from './component/AddToDo';
import TodoListItem from './component/TodoListItem';
import './sass/main.scss';
class App extends Component{
constructor(props){
super(props);
this.state= {
value: '',
list: [],
show: true,
};
this.handleChange= this.handleChange.bind(this);
this.handleSubmit= this.handleSubmit.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.deleteTask = this.deleteTask.bind(this);
}
componentDidMount() {
const list = window.localStorage.getItem('userTodo') ? JSON.parse(localStorage.getItem('userTodo')) : [];
this.setState({ list })
}
handleChange(e) {
this.setState({value:e.target.value})
}
// Handle submission of user todo item
handleSubmit(e) {
e.preventDefault();
const newTask = {
id: Date.now(),
userTodo: this.state.value,
isCompleted: false,
checked: false,
}
// Validate form so user doesn't add an empty to do
if (this.state.value.length > 0) {
this.setState({
list: [newTask, ...this.state.list],
value: '', // Clear input field
show: true, // Success message
}, ()=>{
window.localStorage.setItem('userTodo', JSON.stringify(this.state.list));
})
}
}
// Handles checkbox
handleInputChange(id) {
this.setState({list: this.state.list.map(item => {
if (item.id === id) {
item.isCompleted = !item.isCompleted;
item.checked = !this.state.checked;
}return item
})}, ()=>{
window.localStorage.setItem('userTodo', JSON.stringify(this.state.list));
})
}
// Delete a task
deleteTask(id){
this.setState({list: this.state.list.filter(item => item.id !== id )},()=>{
window.localStorage.setItem('userTodo', JSON.stringify(this.state.list))
})
console.log(this.state.list)
}
render(){
return(
<div>
<Header />
<Info />
<AddToDo onChange={this.handleChange} value={this.state.value} onSubmit={this.handleSubmit} />
<TodoListItem deleteTask={this.deleteTask} onChange={this.handleInputChange} list={this.state.list} defaultChecked={this.state.checked} />
</div>
)
}
}
export default App;
For TodoListItem.js
import React, { Component } from 'react';
import ToDoItem from './ToDoItem';
import '../sass/main.scss';
class ToDoListItem extends Component{
render(){
const {list, onChange, deleteTask, defaultChecked} = this.props;
return(
<div>
{list.map((todo)=>{
return (
<ToDoItem
key={todo.id}
userTodo={todo.userTodo}
isCompleted={todo.isCompleted}
onChange={onChange}
id={todo.id}
deleteTask={deleteTask}
defaultChecked={defaultChecked}
/>
)
})}
</div>
)
}
}
export default ToDoListItem;
For TodoItem.js
import React, { Component } from 'react';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faTrashAlt } from '#fortawesome/free-solid-svg-icons'
import '../sass/main.scss';
class ToDoItem extends Component{
render(){
const {userTodo, isCompleted, onChange, id, deleteTask, defaultChecked} = this.props;
const checkStyle = isCompleted ? 'completed-todo' : 'not-completed-todo';
return(
<div className={`container ${checkStyle}`}>
<input type="checkbox" onChange={onChange.bind(this, id)} defaultChecked={defaultChecked}/>
<div >
<p className='title'>{userTodo}</p>
</div>
{/* Delete button */}
<button onClick={deleteTask.bind(this, id)}><FontAwesomeIcon className='remove-icon' icon={faTrashAlt} /></button>
</div>
)
}
}
export default ToDoItem;
Please note: I have gone through other questions similar to the problem I am having but I could not solve this problem.
If I did not state the question well, please let me know.
In the below code in App.js,
<TodoListItem deleteTask={this.deleteTask} onChange={this.handleInputChange} list={this.state.list} defaultChecked={this.state.checked} />
You are setting, defaultChecked={this.state.checked} Why do you do that? There is nothing called checked in the state.
In fact, there is no need to pass the defaultValue.
Make the following changes,
In App.js, remove defaultValue prop for TodoListItem
<TodoListItem deleteTask={this.deleteTask} onChange={this.handleInputChange} list={this.state.list}/>
In TodoListItem.js, remove defaultChecked={defaultChecked}
<ToDoItem
key={todo.id}
userTodo={todo.userTodo}
isCompleted={todo.isCompleted}
onChange={onChange}
id={todo.id}
deleteTask={deleteTask}
defaultChecked={defaultChecked} // Remove this.
/>
In ToDoItem.js,
<input type="checkbox"onChange={onChange.bind(this, id)}
defaultChecked={isCompleted} // Replace defaultValue with isCompleted
/>
I created a custom redux form component of this react-date-range (https://github.com/Adphorus/react-date-range ). This component somehow unintentionally submits the form when I change the data.
this is my implementation of component
import React from 'react';
import 'react-date-range/dist/styles.css'; // main style file
import 'react-date-range/dist/theme/default.css'; // theme css file
import { DateRange } from 'react-date-range';
class RenderDateRange extends React.Component {
constructor(props) {
super(props);
const initValues = props.input && props.input.value || {};
this.state = {
startDate: initValues.startDate || new Date(),
endDate: initValues.endDate || new Date(),
key: 'selection',
showDatePicker : false
}
}
constructEvent(selection) {
return {
startDate: selection.startDate.getTime(),
endDate: selection.endDate.getTime()
}
}
handleChange(payload) {
this.setState({
...this.state,
...payload.selection
});
this.props.input.onChange(this.constructEvent(payload.selection));
}
render() {
const {input} = this.props;
return (
<div>
<DateRange
{...input}
onChange={this.handleChange.bind(this)}
ranges={[this.state]}
className={'PreviewArea'}
/>
</div>
);
}
}
export default RenderDateRange;
and this is how my form is about
<form className="form" onSubmit={handleSubmit}>
<Field name="eventDate" component={RenderDateRange} />
<button className="btn btn-default btn-save" disabled={submitting || pristine || invalid}>
Save
</button>
</form>
and this is the component that contains the form like:
render() {
const _props = this.props;
return (
<div>
<div className="col-lg-10 col-md-10 col-sm-12 content-container">
{this.renderNotification()}
<NewCustomerForm { ..._props } onSubmit={_props.createCustomer.bind(this, _props.lang)}/>
</div>
</div>
);
}
anyone has a clue what is wrong with my implementation?
========================================================
I also have tried to remove this.props.input and onChange from props of DateRange and it still submits the form.
<DateRange
ranges={[this.state]}
className={'PreviewArea'}
/>
New to React, I have a TextField that I want to "bind" a value to it, I want it to change the value if the user enters value into the TextField and update the TextField if the value change through some API call.
Is there a way to do it ?
You can do this using state and onChange. Simple example included below:
<TextField
onChange={(name) => this.setState({name})}
value={this.state.name}
/>
A guide for updating TextInput based on a variable is located in the docs.
The way to do this in React is with state. Here's an example in JSX:
import React from 'react';
export default class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = {
text: 'default',
text2: 'default'
}
}
onChange(e) {
var obj[e.target.name] = e.target.value
this.setState(obj);
}
render() {
return (
<div>
<input type="text" name="text" value={this.state.text} onChange={this.onChange} />
<input type="text" name="text2" value={this.state.text2} onChange={this.onChange} />
</div>
);
}
}
The same thing with React hook
import React,{useState} from 'react';
export default MyForm = () => {
const [text, setText] = useState('default')
const [text2, setText2] = useState('default')
return (
<div>
<input type="text" name="text" value={text} onChange={(e)=> setText(e.target.value)} />
<input type="text" name="text2" value={text2} onChange={(e)=> setText2(e.target.value)} />
</div>
)
}
Two ways data binding in angular work out of the box by using ngModal directive
NgModal: Creates a FormControl instance from a domain model and binds it to a form control element
import {Component} from '#angular/core';
#Component({
selector: 'example-app',
template: `
<input [(ngModel)]="name" #ctrl="ngModel" required>
<p>Value: {{ name }}</p>
<p>Valid: {{ ctrl.valid }}</p>
<button (click)="setValue()">Set value</button>
`,
})
export class SimpleNgModelComp {
name: string = '';
setValue() { this.name = 'Nancy'; }
}
In ReactJS, we don't have such a built-in option to handle two ways data binding, you need to use the state and add an onChange event to the input.
React Controlled Input allow us to implement data binding in React: we bind a value to a state variable and an onChange event to change the state as the input value changes.
Refer to the below snippet:
class App extends React.Component {
constructor() {
super();
this.state = {name : ''}
}
handleChange = (e) =>{
this.setState({name: e.target.value});
}
render() {
return (
<div>
<input type="text" value={this.state.name} onChange={this.handleChange}/>
<div>{this.state.name}</div>
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
This is pretty straightforward using useState React Hook and TextInput
import { useState } from "react";
import { TextInput, Text, View } from "react-native";
const App = () => {
const [text, setText] = useState("hello");
return (
<View>
<TextInput value={text} onChangeText={setText} />
<Text>Text value: {text}</Text>
</View>
);
};
export default App;
See it working here
In ReactJS, I'm writing a stateless component;
Since I've read avoiding unnecessary states is best practice.
The component represents an input field which executed a function when the input box contains a value.
export const InputField = (props) => {
const InputFieldContentsChanged = (event) => {
props.onChange(event.target.value);
};
return (
<div data-component="input-field"
className={(props.value !== "" ? "value": "")}>
<input type={props.type} value={props.value} onChange={InputFieldContentsChanged} />
<span className="bar"></span>
<label>{props.label}</label>
</div>
);
};
InputField.PropTypes = {
type: PropTypes.oneOf([ "text", "password" ]).isRequired,
label: PropTypes.string.isRequired,
value: PropTypes.string,
onChange: PropTypes.func.isRequired
}
Now,
I've created another component which just is a sample to test the component above.
This looks like the following:
export const SampleComponent = (props) => {
let componentUsername = "";
const onUsernameChanged = (username) => {
componentUsername = username;
};
return (
<InputField type="text" label="Username" value={componentUsername} onChange={onUsernameChanged} />
);
};
So, I'm binding the value to a custom variable in the component which is changed when the contents of the input field does change.
How does it come that the input field component does not update itself with the new username?
Kind regards,
I'm writing a stateless React component since it's best practice to avoid state when not needed.
In your code you are trying to use your own kind of "state" though, and it's just a variable (componentUsername). But since it's not React state, the component does not re-render upon the change of the variable. React simply doesn't know about the change.
So, either use the usual setState instead of re-assigning the your own "state" variable, or put the logic in the parent component and pass the componentUsername to the SampleComponent via props:
const SampleComponent = props => (
<input type="text" onChange={props.onChange} value={props.value} />
);
class ParentComponent extends React.Component {
constructor() {
super();
this.state = { value: '' };
this.handleInputChange = this.handleInputChange.bind(this);
}
handleInputChange(e) {
console.log(e.target.value);
this.setState({ value: e.target.value });
}
render() {
return (
<SampleComponent
value={this.state.value}
onChange={this.handleInputChange}
/>
);
}
}
ReactDOM.render(<ParentComponent />, 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>
The idea of functional components is to not perform any changes to the state or props.
Since there is no trigger to re-render you component you won't see any change.
Change this React.Function to a React.Component.
const InputField = (props) => {
const InputFieldContentsChanged = (event) => {
console.log(event.target.value);
props.onChange(event.target.value);
};
return (
<div data-component="input-field"
className={(props.value !== "" ? "value": "")}>
<input type={props.type} value={props.value} onChange={InputFieldContentsChanged} />
<span className="bar"></span>
<label>{props.label}</label>
</div>
);
};
class SampleComponent extends React.Component {
constructor() {
super();
this.state = { componentUsername : ""};
}
onUsernameChanged = (username) => {
console.log(username);
this.setState({componentUsername: username});
}
render() {
return (
<InputField type="text" label="Username" value={this.state.componentUsername} onChange={this.onUsernameChanged} />
);
}
};
ReactDOM.render(<SampleComponent/>, 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>