Exemplo com React
Componente React com auto preenchimento de endereço via CEP usando hooks (useState + fetch). Digite o CEP e ao sair do campo o endereço será preenchido.
Teste ao vivo
Código fonte do componente
import { useState } from "react";
const API_URL = "";
const API_DISPLAY = "https://consultadecep.com";
function BuscaCep() {
const [cep, setCep] = useState("");
const [endereco, setEndereco] = useState(null);
const [erro, setErro] = useState("");
const [carregando, setCarregando] = useState(false);
async function buscar(valor) {
const cepLimpo = valor.replace(/\D/g, "");
if (cepLimpo.length !== 8) return;
setCarregando(true);
setErro("");
try {
const response = await fetch(`${API_URL}/ws/${cepLimpo}/json/`);
const dados = await response.json();
if (dados.erro) {
setEndereco(null);
setErro("CEP não encontrado.");
} else {
setEndereco(dados);
setErro("");
}
} catch {
setErro("Erro ao consultar o CEP.");
setEndereco(null);
} finally {
setCarregando(false);
}
}
return (
<div style={{ maxWidth: 500, margin: "40px auto", fontFamily: "system-ui" }}>
<h1>Auto Preenchimento de Endereço via CEP</h1>
<p>Digite o CEP e ao sair do campo o endereço será preenchido.</p>
<div style={{ marginBottom: 16 }}>
<label>CEP:</label>
<input
type="text"
value={cep}
onChange={(e) => setCep(e.target.value)}
onBlur={(e) => buscar(e.target.value)}
maxLength={9}
placeholder="00000-000"
style={{ width: "100%", padding: "8px 12px", fontSize: 14 }}
/>
</div>
{carregando && <p>Buscando...</p>}
{erro && <p style={{ color: "red" }}>{erro}</p>}
{endereco && (
<>
<div style={{ marginBottom: 12 }}>
<label>Rua:</label>
<input value={endereco.logradouro} readOnly style={{ width: "100%", padding: "8px 12px" }} />
</div>
<div style={{ marginBottom: 12 }}>
<label>Bairro:</label>
<input value={endereco.bairro} readOnly style={{ width: "100%", padding: "8px 12px" }} />
</div>
<div style={{ marginBottom: 12 }}>
<label>Cidade:</label>
<input value={endereco.localidade} readOnly style={{ width: "100%", padding: "8px 12px" }} />
</div>
<div style={{ marginBottom: 12 }}>
<label>Estado:</label>
<input value={endereco.uf} readOnly style={{ width: "100%", padding: "8px 12px" }} />
</div>
<div style={{ marginBottom: 12 }}>
<label>IBGE:</label>
<input value={endereco.ibge} readOnly style={{ width: "100%", padding: "8px 12px" }} />
</div>
</>
)}
</div>
);
}
export default BuscaCep;