Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
React "append" component to DOM?

I'm new to React and I'm trying to render a component when a user tries to login with wrong login details. I have a Login.jsx page where I render the login form, and handles all the login logic in a async function. This all works fine. If the login details are wrong I have an ErrorModal component render in at an already set div with the ID of error-modal.

ReactDOM.render(<ErrorModal />, document.getElementById('error-modal'))
...

function Login() {
  const userRef = React.useRef()
  const passRef = React.useRef()
  const loginErr = React.useRef()
  const handleLogin = async (e) => {
    e.preventDefault()
    requestLogin(userRef.current.value, passRef.current.value, loginErr)
  }

  return (
    <form className='login-form' onSubmit={handleLogin}>
        <Field ref={userRef} label='Username:' type='text' />
        <Field ref={passRef} label='Password:' type='password' />
        <div className='button-wrapper'>
          <button type='submit' className='btn'>Login</button>
        </div>
        <div id='error-modal'></div>
    </form>
  )
}

export default Login

Do I need to have the error-modal div already in the DOM, or can I just append the ErrorModal component after another DOM element somehow (like inside the form or just outside the form) and not worry about the error-modal div being "hard coded"?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You should use Conditional Rendering.

Here's an example:

function Login() {
  const [userCredentials, setUserCredentials] = useState({
    email: "",
    password: ""
  });

  const [error, setError] = useState(false);

  const handleLogin = async (e) => {
    e.preventDefault();
    try {
      const res = await requestLogin(userCredentials);
      if (!res.ok) {
        throw Error("Login failed...");
      }
    } catch (e) {
      setError(true);
      console.error(e);
    }
  };

  const handleUserCredentialsChange = (e) => {
    setUserCredentials({ ...userCredentials, [e.target.name]: e.target.value });
  };
    
  return (
    <>
      <form onSubmit={handleLogin}>
        <input
          placeholder="Email"
          name="email"
          value={userCredentials.email}
          onChange={handleUserCredentialsChange}
        />
        <input
          placeholder="Password"
          name="password"
          value={userCredentials.password}
          type="password"
          onChange={handleUserCredentialsChange}
        />
        <input type="submit" />
      </form>
      {error && (
        <div style={modalContainer}>
          <div style={{ backgroundColor: "aliceblue", padding: 40 }}>
            <h1>Something went wrong...</h1>
            <button onClick={() => setError(false)}>Close</button>
          </div>
        </div>
      )}
    </>
  );
}

function requestLogin(userCredentials) {
  return fetch("api/login", {
    method: "POST",
    body: JSON.stringify(userCredentials),
    headers: {
      "Content-Type": "application/json"
    }
  });
}

const modalContainer = {
  position: "absolute",
  zIndex: 100,
  top: 0,
  bottom: 0,
  left: 0,
  right: 0,
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  backgroundColor: "rgba(0,0,0,0.5)"
};

Check it out on Code Sandbox if u want to run it in the browser.

about 4 years ago · Juan Pablo Isaza Report

0

you can do it by creating a simple state like this

function Login() {
const [error,setError]=React.useState("")
  const userRef = React.useRef()
  const passRef = React.useRef()
  const loginErr = React.useRef()
  const handleLogin = async (e) => {
    e.preventDefault()
    const res=requestLogin(userRef.current.value, passRef.current.value, loginErr)
//assuming that above function does a post call via fetch
//and also assuming that in case of wrong credentials error was passed from backend
   const data=res.json()
   if(!res.ok) setError(data.error);
     
  }

  return (
    <form className='login-form' onSubmit={handleLogin}>
        <Field ref={userRef} label='Username:' type='text' />
        <Field ref={passRef} label='Password:' type='password' />
        <div className='button-wrapper'>
          <button type='submit' className='btn'>Login</button>
        </div>
        <div id='error-modal'>{error.length>0 && error}</div>
    </form>
  )
}

export default Login
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!