react component reusabilty

33 Views Asked by At
import React, { useState, useEffect, useRef } from 'react';
import Navbar from 'react-bootstrap/Navbar';
import Nav from 'react-bootstrap/Nav';
import NavDropdown from 'react-bootstrap/NavDropdown';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import './StaffReg.css';
import Sidebar from './Sidebar';
import { Layout } from 'antd';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import axios from 'axios';
import { withSuccess } from 'antd/es/modal/confirm';
import { FormLabel } from 'react-bootstrap';
import Tab from 'react-bootstrap/Tab';
import Tabs from 'react-bootstrap/Tabs';
import BootstrapSwitchButton from 'bootstrap-switch-button-react'
import ComboBox from './ComboBox';

const { Header, Content, Footer } = Layout;


function StaffReg() {
    const [selectedValue, setSelectedValue] = useState('');


    const handleSelect = (value) => {
        setSelectedValue(value);
    };

   
    const options2 = ['Section1', 'Section 2', 'Section 3'];
    const options3 = ['Monthly', 'Daily', 'type3'];
    const options4 = ['Branch1', 'Branch2', 'Branch3'];
    const options5 = ['commission1', 'commission2', 'commission3'];
    const options6 = ['ledger1', 'ledger2', 'ledger3'];

    // Add refs for other input fields as needed
    const [formData, setFormData] = useState({

        sr_Name: "",
        sr_Section: "",
        sr_Gender: "",
        sr_Address1: "",
        sr_Address2: "",
        sr_Address3: "",
        sr_Mobile: "",
        sr_Type: "",
        sr_DateOj: "",
        sr_Salary: "",
        sr_OtRate: "",
        sr_OtHour: "",
        sr_LeaveDeduction: "",
        sr_DailyAllowance: "",
        sr_Active: "",
        sr_CasualLeave: "",
        sr_Branch: "",
        sr_CommissionStatus: "",
        sr_Percent: "",
        sr_Pf: "",
        sr_WorkingHours: "",
        sr_Ledger: "",
        sr_UserName: "",
        sr_Password: "",
        sr_AppEnable: "",



    });
    console.log(formData);






    /////combo box ///////

    const handleComboBoxInputChange = (value, fieldName) => {
        // Update the relevant field in the formData state
        setFormData((prevFormData) => ({
            ...prevFormData,
            [fieldName]: value,
        }));
    };



    /////////////////////////////////////////////////////////




    ///////


  
    

    const employeeNameRef = useRef(null);
    const employeeSectionRef = useRef(null);
    const employeeGenderRef = useRef(null);

    const handleKeyDown = (event) => {
        if (event.key === 'Enter') {
          switch (event.target.name) {
            case 'sr_Name':
              // Move focus to the next input field (e.g., employeeSectionRef)
              employeeSectionRef.current.focus();
              break;
            case 'sr_Section':
              // Move focus to the next input field (e.g., employeeIdRef)
              employeeGenderRef.current.focus();
              break;
            // Add cases for other input fields as needed
            default:
              break;
          }
        }
      };
    return (

        <Layout style={{ minHeight: '150vh' }}>
            {/* Use the Sidebar component here */}
            <Sidebar collapsed={collapsed} onCollapse={(value) => setCollapsed(value)} />

            <Layout>

                <div className='staffreg-root-div'>
                   
                    <div className='staff-registration-form'>
                        <div className='staffreg-emp-details-div form-margin'>
                            <div className='employeeId-div'>

                                <FormLabel className='formlabel-employeeId'> Employees Id</FormLabel>
                                <input
                                    value={employeeId}
                                    className=' input-employeeId' />
                            </div>
                            {/* <div className='labelstyle-div'>

                                <FormLabel className='formlabel-labelstyle'> Label Style</FormLabel>
                                <input className='input-labelstyle' />
                            </div> */}
                        </div>
                        <div className='staff-reg-employeeName form-margin'>
                            <FormLabel className='formlabel-employeeName'> Employees Name</FormLabel>
                            <ComboBox
                                ref={employeeNameRef}
                                onKeyDown={handleKeyDown}
                                className="input-employeeName"
                                findedValue={formData.sr_Name}
                                options={employeeNames}
                                onSelect={(value) => handleSelect(value)}
                                onInputChange={(value) => handleComboBoxInputChange(value, 'sr_Name')} // Pass field name to identify the input
                            />


                            <Button className='employee-Rename-Button'> Rename</Button>
                        </div>
                        <div className='staff-reg-emplyee-section form-margin'>
                            <FormLabel className='formlabel-employeeSection'> Section</FormLabel>

                            <ComboBox className='input-employeeSection'
                                ref={employeeSectionRef}
                                onKeyDown={handleKeyDown}
                                setFormData={setFormData}

                                onSelect={(value) => handleSelect(value)}

                                onInputChange={(value) => handleComboBoxInputChange(value, 'sr_Section')}
                                options={options2}
                                findedValue={formData.sr_Section}

                            />


                        </div>
                        <div className='staff-reg-emplyee-genders form-margin'>
                            <FormLabel className='formlabel-employeeGender'> Gender</FormLabel>
                            <div className='gender-radio-buttons-div'>
                                <label>
                                    <input
                                    ref={employeeGenderRef}
                                        type="radio"
                                        name="gender"
                                        value="Male"
                                        onChange={(e) => setFormData({ ...formData, sr_Gender: e.target.value })}
                                    />
                                    Male
                                </label>
                                <label>
                                    <input
                                        type="radio"
                                        name="gender"
                                        value="Female"
                                        onChange={(e) => setFormData({ ...formData, sr_Gender: e.target.value })}
                                    />
                                    Female
                                </label>
                            </div>
                        </div>


                        <div className='staff-reg-emplyee-Address'>

                            <FormLabel className='formlabel-employeeAddress'> Address</FormLabel>

                            <input
                                value={formData.sr_Address1}

                                onChange={(e) =>
                                    setFormData({ ...formData, sr_Address1: e.target.value })
                                } className='input-employeeAddress1 form-margin' />


                            <input value={formData.sr_Address2} ref={(input) => input && (input.name = 'sr_Address2')} onChange={(e) =>
                                setFormData({ ...formData, sr_Address2: e.target.value })
                            } className='input-employeeAddress2 form-margin' />


                            <input value={formData.sr_Address3} onChange={(e) =>
                                setFormData({ ...formData, sr_Address3: e.target.value })
                            } className='input-employeeAddress3 form-margin' />


                        </div>

                        <div className='staff-reg-emplyee-Mobile form-margin'>
                            <FormLabel className='formlabel-employeeMobile'> Mobile</FormLabel>
                            <input value={formData.sr_Mobile}
                                onChange={(e) =>
                                    setFormData({ ...formData, sr_Mobile: e.target.value })
                                } className='input-employeeMobile' />
                        </div>


                        <div className='staff-reg-emplyee-Tabs form-margin'>
                            <Tabs
                                defaultActiveKey="home"
                                transition={false}
                                id="noanim-tab-example"
                                className="mb-3 staff-reg-tab"
                            >
                                <Tab eventKey="home" title="Payroll">
                                    <div className='staffreg-tab-line1 form-margin'>
                                        <div className='employeeType-div'>

                                            <FormLabel className='formlabel-employeeType'> Type</FormLabel>

                                            <ComboBox className=' input-employeeType' setFormData={setFormData}
                                                onInputChange={(value) => handleComboBoxInputChange(value, 'sr_Type')} options={options3} inputClassName='no-border-radius'
                                                onSelect={(value) => handleSelect(value)}
                                                findedValue={formData.sr_Type}

                                            />

                                        </div>
                                        <div className='employeeDateofjoin-div'>

                                            <FormLabel className='formlabel-employeeDateofjoin'> Date Of Join</FormLabel>
                                            <input value={formData.sr_DateOj} onChange={(e) =>
                                                setFormData({ ...formData, sr_DateOj: e.target.value })
                                            } type='date' className='input-employeeDateofjoin' />
                                        </div>
                                    </div>
                                    <div className='staffreg-tab-line2 form-margin'>
                                        <div className='employeeBasicSalary-div'>

                                            <FormLabel className='formlabel-employeeBasicSalary'> Basic Salary</FormLabel>
                                            <input value={formData.sr_Salary} onChange={(e) =>
                                                setFormData({ ...formData, sr_Salary: e.target.value })
                                            } className=' input-employeeBasicSalary' />
                                        </div>
                                        <div className='employeeOtRate-div'>

                                            <FormLabel className='formlabel-employeeOtRate'> O.T Rate</FormLabel>
                                            <input value={formData.sr_OtRate} onChange={(e) =>
                                                setFormData({ ...formData, sr_OtRate: e.target.value })
                                            } className='input-employeeOtRate' />
                                        </div>
                                    </div>
                                    <div className='staffreg-tab-line3 form-margin'>
                                        <div className='employeeOtHour-div'>

                                            <FormLabel className='formlabel-employeeOtHour'> O.T Hour</FormLabel>
                                            <input value={formData.sr_OtHour} onChange={(e) =>
                                                setFormData({ ...formData, sr_OtHour: e.target.value })
                                            } className=' input-employeeOtHour' />
                                        </div>
                                        <div className='employeeLeaveDeduction-div'>

                                            <FormLabel className='formlabel-employeeLeaveDeduction'> Leave Deduction</FormLabel>
                                            <input value={formData.sr_LeaveDeduction} onChange={(e) =>
                                                setFormData({ ...formData, sr_LeaveDeduction: e.target.value })
                                            } className='input-employeeLeaveDeduction' />
                                        </div>
                                    </div>

                                    <div className='staffreg-tab-line4 form-margin'>
                                        <div className='employeeDailyAllowances-div'>

                                            <FormLabel className='formlabel-employeeDailyAllowances'> Daily Allowances</FormLabel>
                                            <input value={formData.sr_DailyAllowance} onChange={(e) =>
                                                setFormData({ ...formData, sr_DailyAllowance: e.target.value })
                                            } className=' input-employeeDailyAllowances' />
                                        </div>
                                        <div className='employeeLeaveDeduction-div'>
                                            <Form.Check
                                                onChange={(e) =>
                                                    setFormData({ ...formData, sr_Active: e.target.checked ? 1 : 0 })
                                                }
                                                className="employee-reg-checkBox custom-checkbox"
                                                label="Active"
                                                aria-label="option 1"
                                            />
                                        </div>

                                    </div>
                                    <div className='staffreg-tab-line5 form-margin'>
                                        <div className='employeeCasualLeave-div'>

                                            <FormLabel className='formlabel-employeeCasualLeave'> Casual Leave/Yr</FormLabel>
                                            <input value={formData.sr_CasualLeave} onChange={(e) =>
                                                setFormData({ ...formData, sr_CasualLeave: e.target.value })
                                            } className=' input-employeeCasualLeave' />
                                        </div>
                                        <div className='employeeBranch-div'>

                                            <FormLabel className='formlabel-employeeBranch'> Branch</FormLabel>

                                            <ComboBox findedValue={formData.sr_Branch} className=' input-employeeBranch' setFormData={setFormData}
                                                onInputChange={(value) => handleComboBoxInputChange(value, 'sr_Branch')} options={options4} onSelect={(value) => handleSelect(value)} inputClassName='no-border-radius' />

                                        </div>
                                    </div>
                                </Tab>
                                <Tab eventKey="profile" title="Details">
                                    <div className='staffreg-tab-line1 form-margin'>


                                        <FormLabel className='formlabel-employeeCommissionStatus'> Commission Status</FormLabel>

                                        <ComboBox findedValue={formData.sr_CommissionStatus} className=' input-employeeCommissionStatus' setFormData={setFormData}
                                            onInputChange={(value) => handleComboBoxInputChange(value, 'sr_CommissionStatus')} options={options5} onSelect={(value) => handleSelect(value)} inputClassName='no-border-radius' />



                                        <FormLabel className='formlabel-employeeCommissionStatusperc'> %</FormLabel>
                                        <input value={formData.sr_Percent} onChange={(e) =>
                                            setFormData({ ...formData, sr_Percent: e.target.value })
                                        } className='input-employeeCommissionStatusperc' />

                                    </div>
                                    <div className='employeePF-div form-margin'>

                                        <FormLabel className='formlabel-employeePF'> P.F</FormLabel>
                                        <input value={formData.sr_Pf} onChange={(e) =>
                                            setFormData({ ...formData, sr_Pf: e.target.value })
                                        } className=' input-employeePF' />
                                    </div>
                                    <div className='employeeWorkingHours-div form-margin'>

                                        <FormLabel className='formlabel-employeeWorkingHours'> Working Hours</FormLabel>
                                        <input value={formData.sr_WorkingHours} onChange={(e) =>
                                            setFormData({ ...formData, sr_WorkingHours: e.target.value })
                                        } className=' input-employeeWorkingHours' />
                                    </div>
                                    <div className='employeeLedger-div form-margin'>

                                        <FormLabel className='formlabel-employeeLedger'> Ledger</FormLabel>

                                        <ComboBox findedValue={formData.sr_Ledger} className=' input-employeeLedger' setFormData={setFormData}
                                            onInputChange={(value) => handleComboBoxInputChange(value, 'sr_Ledger')} options={options6} onSelect={(value) => handleSelect(value)} inputClassName='no-border-radius' />

                                    </div>

                                </Tab>
                                <Tab eventKey="contact" title="Payroll App" >
                                    <div className='employeeUserName-div form-margin'>
                                        <FormLabel className='formlabel-employeeUserName'> UserName</FormLabel>
                                        <input value={formData.sr_UserName} onChange={(e) =>
                                            setFormData({ ...formData, sr_UserName: e.target.value })
                                        } className=' input-employeeUserName' />
                                    </div>
                                    <div className='employeePassword-div form-margin'>
                                        <FormLabel className='formlabel-employeePassword'> Password</FormLabel>
                                        <input value={formData.sr_Password} onChange={(e) =>
                                            setFormData({ ...formData, sr_Password: e.target.value })
                                        } className=' input-employeePassword' />
                                    </div>
                                    <div className='employeePassword-div form-margin'>
                                        <FormLabel className='formlabel-employeePassword'>App Enable</FormLabel>
                                        <BootstrapSwitchButton
                                            onChange={(checked) => setFormData({ ...formData, sr_AppEnable: checked ? 1 : 0 })}
                                            checked={true}  // You may want to use formData.sr_AppEnable instead of always setting it to true
                                            onstyle="primary"
                                            offstyle="light"
                                            size='sm'
                                        />
                                    </div>


                                </Tab>
                            </Tabs>


                        </div>

                    </div>

                </div>
            </Layout>
        </Layout>


    )
}

export default StaffReg
import React, { useState, useEffect } from 'react';
import './ComboBox.css';
import { IoIosArrowDown } from "react-icons/io";

const ComboBox = ({ options, findedValue, placeholder, onSelect, onInputChange, className, inputClassName,inputRef  }) => {
    const [inputValue, setInputValue] = useState(findedValue || '');
    const [isOpen, setIsOpen] = useState(false);
    const [selectedIndex, setSelectedIndex] = useState(-1);
    const [filteredOptions, setFilteredOptions] = useState(options); // New state
   
    useEffect(() => {
        setInputValue(findedValue || ''); // Update input value when findedValue prop changes
    }, [findedValue]);



    const handleInputChange = (event) => {
        const value = event.target.value;
        
        setInputValue(value);

        // Filter options based on the entered value
        const filtered = options.filter((option) =>
            option.toLowerCase().includes(value.toLowerCase())
        );
        setFilteredOptions(filtered);

        // Call the onInputChange prop with the new input value
        onInputChange && onInputChange(value);
    };
    const handleToggleDropdown = () => {
        setIsOpen(!isOpen);
        setIsArrowRotated(!isArrowRotated);
    };

    const handleInputFocus = () => {
        handleInputChange({ target: { value: '' } });
    };
    const handleSelectOption = (option) => {
        setInputValue(option);
        setIsOpen(false);
        onSelect && onSelect(option); // Call the onSelect prop with the selected option
        onInputChange && onInputChange(option); // Update the input value in the parent component
    };

   const handleKeyDown = (event) => {
    if (isOpen) {
        switch (event.key) {
            case 'ArrowUp':
                event.preventDefault();
                setSelectedIndex((prevIndex) =>
                    prevIndex > 0 ? prevIndex - 1 : options.length - 1
                );
                
                break;
            case 'ArrowDown':
                event.preventDefault();
                setSelectedIndex((prevIndex) =>
                    prevIndex < options.length - 1 ? prevIndex + 1 : 0
                );
                break;
            case 'Enter':
                if (selectedIndex !== -1) {
                    handleSelectOption(filteredOptions[selectedIndex]);
                }
                break;
            case 'Escape':
                setIsOpen(false);
                break;
            default:
                break;
        }
    }
};


    useEffect(() => {
        const handleOutsideClick = (event) => {
            if (
                isOpen &&
                event.target.closest('.combo-box-container') === null
            ) {
                setIsOpen(false);
            }
        };

        document.addEventListener('click', handleOutsideClick);

        return () => {
            document.removeEventListener('click', handleOutsideClick);
        };
    }, [isOpen]);
    // Add a state to track whether the dropdown is open or closed
    const [isArrowRotated, setIsArrowRotated] = useState(false);

    return (
        <div className={`combo-box-container ${className}`}>
            <div className="combo-box-input" onClick={handleToggleDropdown}>
                <input
                    type="text"
                    value={inputValue }
                    onChange={handleInputChange}
                    onKeyDown={handleKeyDown}
                    className={`combo-box-input-field ${inputClassName}`}
                    onFocus={handleInputFocus}
                    ref={inputRef}
                />

                {/* <div className={`arrow-icon ${isOpen ? 'rotated' : ''}`} onClick={handleToggleDropdown}>
                    &#9660;
                </div> */}
                <div className={`arrow-icon ${isOpen ? 'rotated' : ''}`} onClick={handleToggleDropdown}>
                <IoIosArrowDown />
                </div>


                {isOpen && (
                    <div className="combobox-dropdown">
                        {filteredOptions.map((option, index) => (
                            <div
                                key={index}
                                className={`dropdown-option ${index === selectedIndex ? 'selected' : ''
                                    }`}
                                onClick={() => handleSelectOption(option)}
                            >
                                {option}
                            </div>
                        ))}
                    </div>
                )}

            </div>
        </div>
    );
};

export default ComboBox;

Here I've created a form page. I've also created a combobox component to implement a dropdown combobox in the staffReg page. Now, I need to implement a functionality to move the focus from one input that's filled to another input when I press the enter key. But since I've used component combobox as an input field in the page I am unable to move focus to that field. How can I achieve that.

0

There are 0 best solutions below