Search code examples
reactjsmaterial-uicomponents

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


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