Call phone or open email client from Material UI TextField

Viewed 941

I have a MaterialUI TextField component, which is some circumstances is disabled and clickable to go to a phone number or email. When this is the case, I want to be able to click on the input and have it behave like an anchor tag with an href, which does not seem to be an option.

Here is the a rough example of what the code looks like:

<TextField
    value={phone}
    onClick={() => {
        console.warn(`Behave like an href to ${phone}`);
    }}
/>

OR

<TextField
    value={phone}
    href={`tel:${phone}`}
/>

I need to know either how to allow TextField to accept and href or how to get the onClick button to behave like an href. What is the proper way of doing so?

Here is a functional sample app of what I am doing with the features I am missing pointed out

1 Answers

You can use window.location.href. If you need the MUI Link component, you could extract a TextFieldLink component that conditionally wraps a TextField with Link based on the disabled prop.

You will probably also want a handleClick handler that provides at least some very basic validation for phone and email.

Disclaimer, I have never used the tel: attribute before, but IIUC this is what you want.

const { TextField, Button, Link } = MaterialUI
const { Fragment, useState } = React

const App = () => {
  const [editMode, setEditMode] = useState(false);
  const [phone, setPhone] = useState('+11234567890');
  const [email, setEmail] = useState('email@email.com');

  return (
    <div>
      <TextField
        label="Phone"
        disabled={!editMode}
        value={phone}
        onChange={(evt) => setPhone(evt.target.value)}
        onClick={() => {
          if (!editMode) {
            window.location.href = `tel:${phone}`;
          }
        }}
      />
      <TextField
        disabled={!editMode}
        label="Email"
        value={email}
        onChange={(evt) => setEmail(evt.target.value)}
        onClick={() => {
          if (!editMode) {
            window.location.href = `mailto:${email}`;
          }
        }}
      />
      <Button onClick={() => setEditMode(!editMode)}>
        {editMode ? 'Save' : 'Edit'}
      </Button>
    </div>
  );
};


ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@latest/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js" crossorigin="anonymous"></script>
<script src="https://unpkg.com/babel-standalone@latest/babel.min.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" />
<div id="root"></div>

Related