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

165
Visualizações
React.js: Input fields and button are in seperate functional components. On clicking, data should be visible in console

I am new to React. My question is....There are Input fields and button in separate functional components. When the user enters the data in the input fields and click button, then the data of the input should be displayed in the console. There is App.js which is parent component and there is Input.js(Child component) and Submit.js(Child component). Submit.js has button. We import Input.js and Submit.js in App.js.

We should validate the input data and on clicking the submit button, if the data is not in correct format, then show error. Other wise, console the data in json format in the console.

I hope you understood the logic. Please send the code for that. I have tried thinking but strucked. Please help me with the code. Thank you

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

0

In App.js

import { useState } from "react";
import Input from "./Input";
import Submit from "./Submit";

export default function App() {
  const [value, setValue] = useState("");

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = () => {
    console.log(value); // do validation with `value`
    console.log(JSON.stringify({ error: "" })); // console JSON data on error
  };
  return (
    <div>
      <Input value={value} handleChange={handleChange} />
      <Submit handleSubmit={handleSubmit} />
    </div>
  );
}

Input.js

export default function Input({ value, handleChange }) {
  return <input type="text" value={value} onChange={handleChange} />;
}

Submit.js

export default function Submit({ handleSubmit }) {
 
  return (
    <button type="submit" onClick={handleSubmit}>
      Submit
    </button>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

the most simple solution will be creating a state at app.js and give input value and onChange props while giving button the submit function with the state value

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. App.js
import React, { useState } from 'react';
import TextInput from './TextInput';
import SubmitButton from './SubmitButton';
const App = () => {
    const [inputVal, setInputVal] = useState(null);
    const [OutPut, setOutPut] = useState({ error: false, errorText:'',correctVal: '' });
    const checkInput = () => {
    if (Number.isInteger(+inputVal) === false)return setOutPut({ ...OutPut, 
          error: true, errorText: 'Input field accept only numbers' });
          //Add API call after validating at below else condition
    else setOutPut({ ...OutPut, error: false, correctVal: inputVal });
    }};
    return (
        <div>
            <TextInput setInputVal={setInputVal} />
            <SubmitButton checkInput={checkInput} />
            {OutPut.error === true ? (
                <h3 style={{ color: 'red' }}>{OutPut.errorText}</h3>
            ) : (OutPut.error===false && OutPut.correctVal !==''?(
                <h3 style={{ color: 'blue' }}>Your input is : {OutPut.correctVal}</h3>
            ):'')}
        </div>
    );
};

export default App;

2.Button

import React from 'react';
const SubmitButton = ({ checkInput }) => {return <button type='button' onClick={() => checkInput()}>Submit</button>};
export default SubmitButton;

3.Input.js

import React from 'react';
const TextInput = ({ setInputVal }) => {
    return (
        <input
            type='text'
            placeholder='Type anything here to see if your input is number'
            onChange={(e) => setInputVal(e.target.value)}
        />
    );
};
export default TextInput;
  1. You can check output on this sandbox link: https://codesandbox.io/s/bold-ishizaka-ktzfu3?file=/src/App.js
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