-1

i am trying to make button and after make button i want to make ad event lisner on by click on this button it will show some message but i am able to create only button but not able to add event listener on it.please help me on it.

function Button()
{
    return (
        <button id='btn'>Masai</button>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(Button());
function showAlert()
{
    return(
        <p>You clicked Masai!</p>
    );
}

const msg=ReactDOM.createRoot(document.querySelector('#message'));
document.querySelector('button').addEventListener('click',()=>{
    msg.render(showAlert());

})

error described in image in console part

2
  • 2
    You need to add event handlers in React not outside it, new docs will guide you beta.reactjs.org/learn/… Commented Nov 5, 2022 at 5:56
  • this is not how things should be done in reactjs. please refer to the docs (reactjs.org/docs/getting-started.html#learn-react) and learn reactjs a little before asking any question like this one here. Commented Nov 5, 2022 at 6:00

1 Answer 1

1

This is not the way that you are trying to do in react.

In Your Index.js

import React from 'react';
    import ReactDOM from 'react-dom/client';
    import './index.css';
    import Button from './Button';
    import reportWebVitals from './reportWebVitals';
    import { BrowserRouter } from 'react-router-dom';
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(
      <BrowserRouter>
        <Button/>
      </BrowserRouter>
    );
    reportWebVitals();

In Your Button.js

 function Button() {
    
    const clickEvent = () => {
    
      alert("You clicked Masai!");
    }
    
      return(
             <button id='btn' onClick={clickEvent}>Masai</button>
        );
    
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.