Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
How to tell if a text field has been changed in React?

I'm having a problem with a react component. It's supposed to test, whenever the field's value is changed, if the value on the field is different from the prop value, but once changed it seems to change the prop too.

 handleChange = (id, event) => {
    this.props.test(id, event.target.value)
    if (this.validate(event.target.value) || (event.target.value === "" && !this.props.required)) {
      this.setState({ valid: true })
      this.props.canSubmit(true)
    }
    else {
      this.setState({ valid: false })
      this.props.canSubmit(false)
    }
    if (event.target.value !== this.props.field_value) {
      this.setState({ changed: true })
    }
    else {
      this.setState({ changed: false })
    }
render() {
    return (
      <div className="mb-3" >
        <link
          rel="stylesheet"
          href="https://fonts.googleapis.com/icon?family=Material+Icons"
        />
        <span>
          <TextField id="outlined-basic" variant="standard" type="text" aria-describedby="emailHelp"
            value={this.props.field_value || ""}
            onChange={event => this.handleChange(this.props.field_id, event)}
            label={this.props.field_label}
            error={!this.state.valid}
          />
          <Icon onClick={this.handleDescription} className="description">help_outlined</Icon>
          {this.state.changed ? <Icon>edit</Icon> : null}
        </span>
      </div>

I've also tried saving the prop value in a state, which also doesn't work. Does anyone have any idea?

Edit:

For more clarification, the problem I'm having is that the prop value is changed whenever the field value is changed, which means that once I change the value in the field, it's always going to think it's different from the original value. For exemple: let's say an email field has a default value of "a@a.com", then I change it to "b@a.com". Now it says it's different, and it's correct. The problem is when I change it back to "a@a.com", now it considers the prop value as the former "b@a.com" and therefore thinks its different even tho it's the same.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You have set flag which is set to true/false in your code, which itself tells you whether or not you have anything in your text field or not. The flag does not tell you what value you have in the text field.

So, it will be something like code below if its what your searching for:

import React, { Component } from "react";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import TextField from "@material-ui/core/TextField";

class MainPage extends Component {
    constructor() {
        super();
        this.state = {
            title: "",
            subtitle: "",
            flag: false,
        };
    }
    handleFilterChange = (event) => {
        this.setState({ [event.target.name]: event.target.value });
        if (this.state.title || this.state.subtitle) {
            this.setState({ flag: true });
        } else {
            this.setState({ flag: false });
        }
    };

    fetchOrdersByQuery = async () => {
        //code for search
    }

    resetFilter = async () => {
        this.setState({
            head: "",
            subhead: "",
            flag: false,
        });
    };

    render() {
        const { classes } = this.props;
        return (
            <Grid>
                <Grid item xs={4}>
                    <TextField
                        fullWidth
                        margin="dense"
                        name="title"
                        label="Title"
                        value={this.state.title}
                        variant="outlined"
                        onChange={this.handleFilterChange}
                    />
                </Grid>
                <Grid item xs={4}>
                    <TextField
                        fullWidth
                        margin="dense"
                        name="subtitle"
                        label="Sub-Title"
                        value={this.state.subtitle}
                        variant="outlined"
                        onChange={this.handleFilterChange}
                    />
                </Grid>
                <Grid item xs={2}>
                    <Button
                        type="submit"
                        fullWidth
                        variant="contained"
                        margin="normal"
                        onClick={this.resetFilter}
                    >
                        {" "}
                        Reset
                    </Button>
                </Grid>
                <Grid item xs={2}>
                    <Button
                        type="submit"
                        fullWidth
                        variant="contained"
                        margin="normal"
                        color="primary"
                        onClick={this.fetchOrdersByQuery}
                    >
                        Search
                    </Button>
                </Grid>
            </Grid>
        );
    }
}


export default (MainPage);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda