12 February 2020

Reusable Textbox component example in react js

  • Create Components folder under src folder
  • Create  common folder under Components folder
  • Create Textbox folder under common folder
  • Add index.js file under Textbox folder and add below Code
import React from "react";
import "./style.css";

const Textbox = props => {
  return (
    <input
      id={props.id}
      name={props.name}
      type={props.type}
      placeholder={props.placeholder}
      className={props.className}
      onChange={props.onChangeHandler}
      readOnly={props.isreadOnly}
      value={props.value}
    />
  );
};
Textbox.defaultProps = {
  type: "text",
  className: "txtStyle1",
  isreadOnly: false
};
export default Textbox;
  • Add style.css file and add below Code
.txtStyle1 {
  width100%;
  padding12px 20px;
  margin8px 0;
  displayinline-block;
  border1px solid #ccc;
  border-radius4px;
  box-sizingborder-box;
}

.txtStyle2 {
  width100%;
  padding12px 20px;
  margin8px 0;
  displayinline-block;
  border1px solid #f00;
  border-radius4px;
  box-sizingborder-box;
}
  • Go to Components Folder and Add TextboxEXP.js file and add below Code
import React, { useState } from "react";
import Textbox from "./common/Textbox/index";

const TextboxEXP = () => {
  const [txtNamesettxtName] = useState("");
  const [txtEmailsettxtEmail] = useState("Default Data");
  const [txtPasswordsettxtPassword] = useState("");
  return (
    <>
      <h3>Textbox reusable component example</h3>
      <Textbox
        id={"txtName"}
        name={"txtName"}
        type={"text"}
        placeholder={"Enter Name"}
        className={"txtStyle1"}
        isreadOnly={false}
        value={txtName}
        onChangeHandler={e => settxtName(e.target.value)}
      />
      <Textbox
        id={"txtEmail"}
        name={"txtEmail"}
        type={"text"}
        placeholder={"Enter Email"}
        className={"txtStyle1"}
        value={txtEmail}
        onChangeHandler={e => settxtEmail(e.target.value)}
      />
      <Textbox
        id={"txtPassword"}
        name={"txtPassword"}
        type={"password"}
        placeholder={"Enter Password"}
        className={"txtStyle2"}
        value={txtPassword}
        onChangeHandler={e => settxtPassword(e.target.value)}
      />
    </>
  );
};
export default TextboxEXP;
  • Open App.js file and update code as below
import React from 'react';
import TextboxEXP from './Components/TextboxEXP'

function App() {
  return (
    <div>
      <TextboxEXP/>
    </div>
  );
}

export default App;

Output:



No comments:

Post a Comment