Reputation: 431
how when loading a page to click on a button in react?
I need a button to be pressed when the page loads
https://codesandbox.io/s/gifted-poitras-3sknp
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<button onClick={() => alert("loaded")}>button</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Upvotes: 1
Views: 3690
Reputation: 469
From React's Hooks API Reference
The function passed to useEffect will run after the render is committed to the screen.
So you can always consider to use useEffect to run whatever side effects do you want right after the page rendered. Make sure to pass []
as the second argument to make sure the arrow function will only be called once.
This is an alternative example of using the useEffect hook with document.getElementById(id)
instead of useRef
since that has already been mentioned
It is still better to use useRef
especially if the component will be reusable in the same page.
import React, {useEffect} from "react";
useEffect(() => {
document.getElementById("btn").click();
},[]);
function App() {
return (
<div className="App">
<button id="btn" onClick={() => alert("loaded")}>button</button>
</div>
);
}
Upvotes: 1
Reputation: 3443
Are you looking for something like this. Button clicks happens on page load and also when clicked on button?
class App extends React.Component {
constructor(){
super();
this.buttonClicked = this.buttonClicked.bind(this);
}
componentDidMount(){
this.buttonClicked();
}
buttonClicked(){
alert("I'm Clicked");
}
render() {
return (
<button onClick={() => this.buttonClicked()}>
button
</button>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Upvotes: 2
Reputation: 11790
use useRef
to save a reference to the button
element combined with useEffect
to detect when the component mounts
import React, { useEffect, useRef } from "react";
function App() {
const buttonRef = useRef(null);
useEffect(() => {
buttonRef.current.click();
}, []);
return (
<div className="App">
<button ref={buttonRef} onClick={() => alert("button")}>
button
</button>
</div>
);
}
Upvotes: 1