skip to Main Content

Basically I have an onClick function for a button I made, and I want the functionality of it to be that clicking that button creates a NEW button.

How would I create a new button that shows up on the screen, but only when the original button has been clicked?

The button I made:

<ARButton onClick={addRelay}>Add Relay</ARButton>

And the function it calls:

const addRelay = (e: React.MouseEvent<HTMLButtonElement>) => {
        e.preventDefault();

        // call backend addRelay

        if (relayname !== '') {
            console.log('Relay Name: ' + relayname);
            setRelayName('');
            // how to create a new button here?
        }
    };

4

Answers


  1. All you need is a state managing the condition to show the new button or not.
    Initially the state’s value is false (as you described, it should show only after a click). Then you just need to change the state upon click button event.

    Here is the code for doing so:

    import React, { useState } from "react";
    import ReactDOM from "react-dom";
    
    function App() {
      const [showNewButtonState, setShowNewButtonState] = useState(false);
    
      const onClickOriginalButton = () => {
        setShowNewButtonState(() => true);
      }
    
      return (
        <>
          <button onClick={onClickOriginalButton}>ORIGINAL</button>
          {showNewButtonState && (
            <button>NEW</button>
          )}
        </>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    
    Login or Signup to reply.
  2. It’s the same as just about any other change you might make in your component: You do it via state (of whatever your favorite kind of state mechanism you like). The button sets the state that tells your component it should render the new button. The state member might be a simple flag, or an array if you want to create multiple buttons, etc.

    Here’s a simple example using useState, but it’s fundamentally the same if you use other state mechanisms:

    const { useState } = React;
    
    const Example = () => {
        const [buttonClicked, setButtonClicked] = useState(false);
    
        const handleMainClick = () => {
            // Here I'm toggling on click, but you could just set it, or add to an
            // array, or...
            setButtonClicked((flag) => !flag);
        };
        const handleNewButtonClick = () => {
            console.log("New button clicked");
        };
        return (
            <div>
                <input type="button" value="Click Me" onClick={handleMainClick} />
                {buttonClicked && (
                    <input
                        type="button"
                        value="New Button"
                        onClick={handleNewButtonClick}
                    />
                )}
            </div>
        );
    };
    
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<Example />);
    <div id="root"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

    Or an array of buttons:

    const { useState } = React;
    
    const Example = () => {
        const [buttons, setButtons] = useState([]);
    
        const handleMainClick = () => {
            // Here I'm toggling on click, but you could just set it, or add to an
            // array, or...
            setButtons((buttons) => [...buttons, `Button #${buttons.length + 1}`]);
        };
        const handleNewButtonClick = ({ currentTarget: { value } }) => {
            console.log(`${value} clicked`);
        };
        return (
            <div>
                <input type="button" value="Click Me" onClick={handleMainClick} />
                {buttons.map((button) => (
                    <input
                        key={button}
                        type="button"
                        value={button}
                        onClick={handleNewButtonClick}
                    />
                ))}
            </div>
        );
    };
    
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<Example />);
    <div id="root"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
    Login or Signup to reply.
  3. Create a state with a list of button objects. Each time you click the button, add a button to your state.

    Next, map the buttons to button elements.

    const [buttons, setButtons] = useState([]);
    
    const onClickhandler = (caption, onClick) => {   
        SetButton(prevButtons => [...prevButtons, { caption, onClick }] 
    }
    
    const buttonElements = buttons.map(button => <button onClick={button.onClick}>{button.caption}>
    
    ...etc
    

    All you have to do next is output your original button an on click call the function, providing a caption and an on click action for the new button!

    Login or Signup to reply.
  4. You can create a state like displayCreatedButton and in your condition
    // how to create a new button here?
    you can setDisplayCreatedButton(true)

    Then conditionally render it in your component.

    Full sample

    export const SampleComponent = () => {
      const [displayCreatedButton, setDisplayCreatedButton] = useState(false)
      const addRelay = (e: React.MouseEvent) => {
         e.preventDefault();
         // call backend addRelay
         if (relayname !== '') {
            console.log('Relay Name: ' + relayname);
            setRelayName('');
            setDisplayButton(true)
         }
      };
        return (
        <>
           {displayCreatedButton && <Button>Hi</Button>}
           <ARButton onClick={addRelay}>Add Relay</ARButton>
        </>
        )
    
    }
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search