Search code examples
reactjselectronrenderapplicationcontextstateless

Add Input Field onClick stateless component React Electron


I'm new to electron, and working on trying to get React/Typescript with Hooks and ApplicationContext to all come together. I didn't create the framework and I need to learn how to make this work. Just setting the context to avoid answers like, use Redux instead. :)

I have a function stateless component that is a form. It needs to be stateless so I have access to values that are held in ApplicationContext. I'm trying to render extra input fields on button click, and so far when I click the button Electron calls the method, and then re-renders. I have searched high and low, and have been banging my head on this for a few hours. I apologize in advance if there is already an answer out there.

So far the code that displays the button looks as such:

<div className="form-group">
    <button onClick={() => addUrls()}>
        Add a URL
    </button>
</div>

And the method is just printing to the console at the moment. It looks as such:

const addUrls = () => {
    console.log('clicked')
}

the print statement is getting to the console, and then Electron re-renders. The rest of the component's methods are called, and are behaving in a predictable way. I'm really confused as to why this particular action is causing renders. If anyone can point me in the direction of an answer, or point out where I am doing something dumb in my code, I would be very much grateful.


Solution

  • Turns out I was doing something dumb. Because my button is inside a form, and I didn't specify the button type, it was doing the default behavior of "submit" which causes a render with the onClick.

    The solution was to add type="button" to the button and now it's solved.

        <div className="form-group">
            <button onClick={addUrls} type="button">
                Add a Reference URL
            </button>
        </div>
    

    I hope this can save someone some time if they come across this problem in the future.