Home > Blockchain >  React Make re-usable input field for URL to replace non http to http
React Make re-usable input field for URL to replace non http to http

Time:02-22

I am trying to write a reusable component for the input field for URL

import React from 'react';


const InputURL = ({ nam, ...rest}) => {

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

export default InputURL; 

I want when user input facebook.com then in onChange it should return with http like it will be https//facebook.com

I will use only this <InputURL onChange={(e) => console.log(e)} />

Can anyone please tell me how can i override onChange to replace non http to http?

Note: I want to write the condition once in the InputURL component only, dont want to write everywhere where i will use it

CodePudding user response:

onChange event may trigger many time so it would be better if you make your logic to add "http" on blur event like this.

import React from 'react';

const InputURL = ({ name, callback, ...rest }) => {
  const [value, setValue] = React.useState('');

  return (
    <>
      <input
        onBlur={() => callback(`http://${value}`)}
        name={name}
        onChange={(e) => setValue(e.target.value)}
        {...rest}
      />
    </>
  );
};

export default InputURL; 

and in the component where you are using this component find parameter coming in callback. for example I am logging here.

import React from 'react';
import './style.css';
import InputURL from './InputURL';
export default function App() {
  const callback = (val) => {
    console.log('>>>>>', val);
  };
  return (
    <div>
    
      <InputURL callback={callback} name="My Input" />
    </div>
  );
}

See SS hope you are looking the same.enter image description here

CodePudding user response:

import React from 'react';


const InputURL = ({ nam, prefix, ...rest}) => {

return (
    <>
    <input
        name={nam}
        id={"input-" nam}
        onChange={(e) => {
            const value = e.target.value;
            const input = document.querySelector('#input-' nam);
                if(value.substring(0,prefix.length) != prefix)
                {
                    input.value = prefix;
                } 
        }}
        {...rest}
        />
    </>
);
}
export default InputURL;

This should work, check it out the reference of Substring here.

  • Related