Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make reusable component with optional props.onBlur function in react JS?

I have a TextField component

return (
    <TextField 
        label={props.label} 
        name={props.name}
        placeholder={props.placeholder} 
        type={textFieldType === 'password' ? props.type : textFieldType}
                    
        onBlur={(event) => props.handleOnBlur(event)} //after focus lost
        onChange={(event) => props.handleOnChange(event)}   //
        
        value={props.value}
    ></TextField>
)

Use the TextField component

//FirstName
<MyTextField
    type={inpValues.firstName.type}
    label={inpValues.firstName.label}
    name={inpValues.firstName.name}
    placeholder={inpValues.firstName.placeHolder}

    handleOnChange={
        (event) => {console.log('onChange called =' + event.target.value)}
    }

    value={inpValues.firstName.value}
    >
</MyTextField>

//Email Address
<MyTextField
    type={inpValues.email.type}
    label={inpValues.email.label}
    name={inpValues.email.name}
    placeholder={inpValues.email.placeHolder}

    handleOnBlur={
        (event) => {console.log('onBlur called =' + event.target.value)}
    }
    handleOnChange={
        (event) => {console.log('onChange called =' + event.target.value)}
    }

    value={inpValues.email.value}
    >
</MyTextField>

I want to call handleOnBlur only specific TextField. I don’t want to call for all the TextField

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can make this optional in the prop, and then on your textfield only run the function if it’s provided, something like this:

return (
    <TextField 
        label={props.label} 
        name={props.name}
        placeholder={props.placeholder} 
        type={textFieldType === 'password' ? props.type : textFieldType}
        onBlur={(event) => {
          if (props.handleOnBlur) {
            props.handleOnBlur(event)
          }
        }} //after focus lost
        onChange={(event) => props.handleOnChange(event)}   //
        
        value={props.value}
    ></TextField>
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading