i'm trying to create a ZIP code input that loads street, state and city values automatically in a Create form using React-Admin. How can I populate the inputs based on the onBlur
event of the zip code input?
The best result i achieved is the following scenario:
I created a custom component that has 4 Inputs: zip code (in my country is called CEP), street address, state and city. Then I added an onBlur
event on the zip input and set the value on the inputs based on state attributes. Here is the code
class CustomAddressInput extends React.Component {
constructor(props){
super(props);
this.state = {
cep : '',
address : '',
uf : '',
city : '',
}
this.setAddress = this.setAddress.bind(this);
}
setAddress(e){
if(e.target.value != undefined){
endereco(e.target.value).then((result)=>{
this.setState({
cep: result.cep,
address: result.logradouro,
uf: result.uf,
city: result.localidade
});
});
}
}
render() {
const { classes } = this.props;
return (
<TextInput label="CEP" source="cep" onBlur={(e) => this.setAddress(e)} defaultValue={this.state.cep} />
<TextInput label="Endereco" source="address" defaultValue={this.state.address}/>
<SelectInput label="Estado" source="state" choices={stateList} defaultValue={this.state.uf}/>
<TextInput label="Cidade" source="city" defaultValue={this.state.city}/>
);
}
}
export default withStyles(styles)(CustomAddressInput);
And i'm using it on a Create
...
<Create {...props}>
<SimpleForm>
<TextInput label="Nome" source="name"/>
<TextInput label="CPF/CNPJ" source="cpfcnpj"/>
<TextInput label="Email" source="email"/>
<TextInput label="Senha" source="password" type="password" />
<TextInput label="Telefone" source="phone" type="tel"/>
<CustomAddressInput/>
<BooleanInput label="Pode criar outros usuários do sistema" source="canCreateUser" defaultValue={false}/>
<BooleanInput label="Pode gerenciar projetos" source="canCreateProjects" defaultValue={false}/>
<BooleanInput label="Pode visualizar honorários" source="canSeeFees" defaultValue={false}/>
</SimpleForm>
</Create>
...
I know i'm setting the values in a wrong way because when the values are set, all the create form is wiped. What should i do? I'm not familiar developing with React. Thanks in advance
I think i found the proper way of doing this. I moved the auto fill address function to a
onChange
event on the SimpleForm element and removed it from the CEP input. It works like a charm now. Here is the code:Custom Address input
And the Create Component