How to properly render a success message upon clipboard click and copy - javascript

I'm creating a color palette where I have a clipboard icon within a Tooltip component next to each color. On click it will copy the color's name onto the user's clipboard. When that happens, the Tooltip's message should change from "copy" to "copy success". I'm having issues trying to display the success message individually for each color.

All of you Tooltip components are using the same parent state this.state.copyMessage. If you click copy on one, that sets this.state.copyMessage to "copy success", and it gets rerendered for all other Tooltips. You need to be able to either:
identify who was clicked,
give state to each Tooltip,
add one state entry per tooltip.
I'd personally go with a way to identify who was clicked.
Global declaration
const PROMPT_MESSAGE = "Copy to clipboard"
const CLICKED_MESSAGE = "Copied!"
Set your state onClick
setState({ clickedColor: color.name });
Get the appropriate message for the specific color
const tooltipTitle = this.state.clickedColor === color.name
? CLICKED_MESSAGE
: PROMPT_MESSAGE
Pass in the title
<Tooltip title={tooltipTitle} placement="right">
</Tooltip>
There are many ways to work around this, and this is just one I find readable!

Try passing 'event' as a parameter to your onClick function and using the stopPropagation() method. Like so:
<Tooltip title={copyMessage} placement="right">
<span
onClick={(event) => {
event.stopPropagation()
copyNameToClipboard(color.name);
setState({
copyMessage: 'copy success',
});
}}
>
This should stop your event from 'bubbling up' to other components:
https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

Related

How to prevent select event from firing after every input?

I'm trying to create a custom text editor in React, thus I've created a div which has a contentEditable attribute. Now I want to perform some action when the user selects a part of the inputted text. To do that I'm using the select event as onSelect attribute on my div. The problem is that, select event runs not only when selecting the text, but also when I click on the input box, or after any input. How can I prevent it, so that it gets fired only when the text is selected ?
Component:
function EditorBody(props) {
return (
<div className="editor-body">
<div
className="text-section"
contentEditable
role="textbox"
placeholder="Text goes here ..."
onSelect={() => window.alert("You've selected a text")} // Runs after every input, not only when the text is selected
></div>
</div>
);
}
export default EditorBody;
You can change the logic in your onSelect to be able to determine whether or not to execute the selected logic.
onSelect={(event) => {
if (document.getSelection().toString().length > 0) {
// your selection logic
window.alert(document.getSelection().toString());
}
}}
This way the logic will be executed only if the user is selecting something and not on other primary events that might set off the secondary select event (focus, keypress, etc).

How to get focus from click event of a text to googleplaces autocomplete input?

need your help for an app iam trying to develop. So I have used react native googleautoplaces complete for the location, which is shown in the first text input.
The page when loaded gets the current location based on geocoder, geolocation codes i have used.
What i need is that, when i click on the 'change' link, it should focus or select the location input.page design,code for google autocomplete,code2.
If i use ref, can i do like that. If yes, how to add multiple ref, because already another ref is used in the autocomplete.ref method used inside autocomplete, which takes the address value.
<GooglePlacesAutocomplete
...
ref={(ref) => { this.ref_location = ref }
//your element where the "Change" is being pressed. I used a button just as an example
<Button
title="Change"
onPress={() => { this.ref_location.focus(); }}
/>

ReactJS - How does one delete a button component, that was just clicked?

My aim is to delete the button, I have just clicked. I understand there may be numerous ways such as creating a deleteButton component, and setting the state appropriately.
However, my return function in the main App component will also render another button (this I can do), but I think this may add to the complexity.
I'm currently struggling to pin-point the ideal solution, so please help.
Okay, so I've managed to solve my question, although I'm sure there's other ways too.
To further clarify...
I had a form which I wished to render, when clicking on a 'Create' Button.
At the same time, I wished to remove the 'Create' button, once clicked.
The end result is to only display the form and nest a new button in the return function.
1) Set the initial state of the form to false:
this.state = {
displayForm: false,
}
2) Then use setState within the displayForm function to allow for the change in state, once the button is clicked:
displayForm(){
this.setState({
displayForm: !this.state.displayForm {/* true */}
})
}
3) set a style object within the render function, such as:
render() {
const btnStyle = {
display: 'block',
} ...
4) Use an IF statement to change the display style of the button if the form has been rendered
if(this.state.displayForm){
btnStyle.display = 'none'
}
5) Now, within the return function, use your JSX tags appropriately and call the function onClick, as well as the style to be applied.
<Button
style={btnStyle}
onClick={() => {
this.displayForm()
}}>Create</button>
{this.state.displayForm && ([
<Form />,
<br />,
<Button>Add Schema</Button>,
])}
NOTE: the < Form /> and < Button /> components have been imported and added here.
So, once the 'Create' button has been clicked, the form displays (true), and thereby the 'Create' button disappears from the Virtual DOM. I've also nested another (new) button as intended, underneath the form.

Check for a value onClick react

In my render method i render some cards that all have button and when i click on the button i want to disabled them.
Those buttons are checking if the value of the array is true and if it is it's disabling the button but this is only working when i refresh the page and i want the button to be disabled directly on click
Here is my try
//this is checking from my database if it include the id of the pokemon that i want to get
const check = pokemon.id
const newPoke = getPokemon.includes(check);
// Here is the button that is getting disabled only if newPoke return true
<Button isDisabled={newPoke}/>
Everything work correctly when i refresh the page the buttons that i clicked previously get disabled but not onClick directly.
I think after i click i have to re-check for newPoke but i'm not sure how to include it in the button
You are using props to pass variable from parent to children(Button).
reactjs documentation states react props are read-only
If you are planing to change the values of newPoke then you should rethink your structure and maybe its best to use states in your example
For example here
<Button isDisabled="newPoke"></Button will only be checked at initialization stage since its a react prop. but if you used state which gets updated with every new action you can have a true one-way binding and your ui would reflect data changes quickly
store the newPoke in state and change it's value when the button is clicked. and use that value in button isDisabled prop. try something like this
state={
isDisabled: false;
}
handleClick=(isDisabled)=>{
this.setState({isDisabled});
}
//this is checking from my database if it include the id of the pokemon that i want to get
const check = pokemon.id
const newPoke = getPokemon.includes(check);
// Here is the button that is getting disabled only if newPoke return true
return(
<Button isDisabled={this.state.isDisabled} onClick={()=>this.handleClick(newPoke )}/>
);
i think if you want get value from database you can use componentDidMount().
and your value you can save while in state. and then in function handleClick you can change this state
for example :
handleClick = () => {
const value = this.state.valueFromDataBase
this setState({valueFromDataBase: false})
}
and in render you declare this value state
render(){
return(
<Button defaultValue={this.state.valueFromDataBase} onCLick={this.handleClick} />
)
}
please correct my answer if I am wrong in responding to your question

How to add disabled attribute via prop to a button in react?

I am creating a custom button component in react. I want to pass a prop to that button, based on the value of which button gets enabled or disabled.
My problem is
- The mere presence of the disabled property disables the element, so I cannot set its value as "false". Even the following code is disabling the element
<input type="button" id="myBtn" value="Submit" disabled="" />
I need to either remove the attribute completely or set its property via javascript.
document.getElementById("myBtn").disabled = true;
My custom button component is -
import React from 'react';
const CustomButton = ({ whenClicked, classNames, buttonText, isDisabled }) =>
(
<button
onClick = {whenClicked}
className = {`btn ${classNames}`}
type = "button"
disabled = {isDisabled}
>
{buttonText}
</button>
);
export default CustomButton;
isDisabled is a boolean value.
One more thing, I lost the default submit behavior of button while using custom button. Now I always need to pass a click handler. Is there any way to achieve the same behavior again?
What you currently have should work perfectly fine. Be careful that when you use CustomButton you don't send in the value for disabled as a string. That will make it disabled regardless of what you pass in. Instead, you need to pass in a boolean, that's in JSX syntax.
Here's a sample usage where you would put it inside of a render function of a component that uses the button:
...
render() {
<div>
...
<CustomButton
whenClicked={() => console.log('I just got clicked')}
buttonText="Some Button"
isDisabled={false}
/>
...
</div>
}
...
Basically, instead of false you could pass in something else. You could pass in a boolean value that's stored on the props of the container that holds the CustomButton.
You could say isDisabled={this.props.disableInnerButton} and it would work as you would expect. Changing the value of the boolean will disable or enable the button.
Below you can find a relevant answer I gave recently on a very similar topic:
Statement to add or not an attribute in JSX
At first it looks quite complicated to handle but, if we look at the problem I think we can achive it using css only by adding a class(selector) to the element
.disabled { pointer-events: none;}
or conditionally styling:
<button style={{pointerEvents: notValid ? "none" : "initial"}}> Submit </button>

Categories