Home > OS >  React.js: Input fields and button are in seperate functional components. On clicking, data should be
React.js: Input fields and button are in seperate functional components. On clicking, data should be

Time:02-18

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

CodePudding user response:

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>
  );
}

CodePudding user response:

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

CodePudding user response:

  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
  • Related