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
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:
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:Or an array of buttons:
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.
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!
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