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

Why do I receive null when i pass this id?

import React from "react";
import MailIcon from "@material-ui/icons/Mail";

export default function App() {
  return (
    <div className="App">
      Pass: <input type="password" id="pass"/>
      <MailIcon onClick={showPass("pass")}/>
    </div>
  );
  function showPass(e)
  {
    console.log(e);
    var pass = document.getElementById(e);
    console.log(pass);
    if(pass.type === "password")
    {
      pass.type="text";
    }
    else
    {
      pass.type ="password";
    }
  }
}

I am calling a simple function to change the type of the field to text but I don’t know why it is showing me this error

Error-page

Console-log

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

When I console log the e it shows the "pass" name but when i pass to getElementById it converts to null.

>Solution :

Instead of using native DOM methods you need to start thinking in React, and use state. You can then click the icon to call a function to update the type state (initially set to ‘password’) which will be reflected in the new render.

const { useState } = React;

function Example() {

  // Initialise the state
  const  [type, setType] = useState('password');

  // Set the new state when the main icon is clicked
  function changeType() {
    const newType = type === 'password' ? 'text' : 'password';
    setType(newType);
  }

  // Capitalise the label
  function capitalise(str) {
    return `${str[0].toUpperCase()}${str.substr(1, str.length)}`;
  }

  return (
    <div>
      {capitalise(type)}: <input type={type} />
      <button onClick={changeType}>Mail icon</button>
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
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