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
When I console log the e it shows the "pass" name but when i pass to getElementById it converts to null.
CodePudding user response:
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>
CodePudding user response:
Change onClick={showPass("pass")}
to onClick={()=>showPass("pass")}
CodePudding user response:
Your code has multiple the mistake:
1- Don't use getElementById in the react.
2- You must use from e.target instead e, for referring to element.
1,2 => var pass = e.target; .
3- Even so, in the your If, pass.type is null! because MailIcon not have a type attribute.(the input tag has a type attribute)
CodePudding user response:
You Just Need To Implement Function Like This :
onClick={() => showPass("pass")}