Home > Back-end >  Reactjs not calling onChange callback in child
Reactjs not calling onChange callback in child

Time:02-22

I have written a re-usable input component for url if a url dont start with http then it will be added http in the beginning.

Here you go for the componet

import React, {useContext, useCallback} from 'react';


const InputURL = ({ name, onChange, ...rest}) => {


    const sanitizeURLonChange = React.useCallback((value, actionMeta) => {
        if (value.target.value) {
            if (!value.target.value.startsWith('http')) {
                value.target.value = 'http://'   value.target.value
            }
        }

    }, [onChange])


    return (
        <>
           <input
               name={name}
               {...rest}
               onChange={sanitizeURLonChange}
            />
        </>
    );
}

export default InputURL;

But when i try to use it in my some component, the onChange doesn't work

I try this way

<InputURL onChange={(e) => console.log(e.target.value)}  />

unfortunately the inputURL onChange not working anymore, can you please help me in this case?

I want to achieve. if user input url without http, it will add http,

Like i input it stackoverflow.com/ and then it will return https://stackoverflow.com/ in Onchange

CodePudding user response:

I think your problem is here:

value.target.value = 'http://'   value.target.value

You are trying to update input value by not using an hook.

Try to rewrite your code in this way:

import React, { useState } from 'react';


const InputURL = ({ name, onChange, ...rest}) => {
    const [val, setVal] = useState("");

    const sanitizeURLonChange = (value, actionMeta) => {
        if (value.target.value) {
            if (!value.target.value.startsWith('http')) {
                setVal('http://'   value.target.value);
            }
            else setVal(value.target.value);
        }
    }


    return (
        <>
           <input
               name={name}
               {...rest}
               value={val}
               onChange={sanitizeURLonChange}
            />
        </>
    );
}

export default InputURL;

Here codesandbox working example.

CodePudding user response:

You are closing the bracket right after the event argument : {(e)}. Try like this:

<inputURL onChange={(e, val) => console.log(val)}  />

also you have to use the onChange you're passing as props:

const sanitizeURLonChange = (e, actionMeta) => {
    let newValue = e.target.value
    if (newValue) {
        if (!newValue.startsWith('http')) {
              newValue = "http://"   newValue
            
        }
    }
    setVal(newValue);
    onChange(event, newValue)
}

but it seems anyway the onChange you are passing as a props to inputURL is not used anywhere so I am not sure what you want to achieve. Also you are calling the component inputURL instead of InputURL and first letter uppercase is very important in JSX.

  • Related