Search code examples
javascriptreactjseventseventhandler

How to fix a Function for Button click event executes on page load


In my MERN app I am trying to take a screenshot of a portion of the webpage to send it to the database with other info that is submitted such as submitter and description. The problem is, the image is only saved after I ctrl+S in my editor, not when I click the button or when I refresh the page. How can I fix this? Also, I would appreciate some direction in how to store the png and how to save it in the database.

import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { createPost } from '../../actions/posts'
import domtoimage from 'dom-to-image';

import './form.css';

const Form = () => {

    const [postData, setPostData] = useState({
        submittor: '', description: ''
    })
    const dispatch = useDispatch();
    
    const handleSubmit = (event) => {
        event.preventDefault();
        dispatch(createPost(postData));
    }

    function saveImg(){
        domtoimage.toBlob(document.getElementById('main'))
    .then(function(blob) {
      window.saveAs(blob, 'test');
    });
    }
    
    return(
        
        <div className='form'>
            <form autoComplete='off' noValidate onSubmit={handleSubmit}>
                <h1>Submit Position</h1>
                    <label className='label' for='submittorName'>Your Name</label>
                    <input name='submittor name' id='submittorName' type='text' variant='outlined' placeholder='Your name...' value={postData.submittor} onChange={(event) => setPostData({...postData, submittor: event.target.value})}/>
                    <label className='label' for='description'>Description</label>
                    <input name='description' id='description' type='text' variant='outlined' placeholder='Description...' value={postData.description} onChange={(event) => setPostData({...postData, description: event.target.value})}/>
                    <button type='submit' className='button' onClick={saveImg()}>Submit</button>
            </form>
        </div>
    )
}

export default Form;

Solution

  • You should remove () so the function is executed on js file loading.

    onClick={saveImg()} ---> onClick={saveImg}
    

    More details here

    And common mistakes like yours have been addressed here