I am creating a geography game where you are supposed to click on a specific country on a world map - if you click on the right one, the country changes color and the game presents a new country to be clicked at. If the player doesn't know, he can click on a button which will show him the correct answer. For this, I want to simulate a click event, so that the same onClick() function is called as if you clicked on the correct country.
I am using D3, and the world map is made up of svg paths. Below is the code I thought would work, using the HTMLElement.click() method:
function simulateClick() {
// for each index in the nodelist,
// if the properties are equal to the properties of currentTargetUnit,
// simulate a click on the path of that node
let nodelist = d3.selectAll(".unit")
for (let i = 0; i < nodelist._groups[0].length; i++) {
if (nodelist._groups[0].item(i).__data__.properties.filename === currentTargetUnit.properties.filename) {
console.log(nodelist._groups[0][i])
// logs the correct svg path element
nodelist._groups[0][i].click()
// logs TypeError: nodelist._groups[0][i].click is not a function
}
}
}
I then looked at some tutorials which say that, for some reason I don't fully understand, you rather need to use React.useRef for this - but in all their examples, they put a "ref" value on an element which is returned from the beginning in the React component, like so:
import React, { useRef } from "react";
const CustomTextInput = () => {
const textInput = useRef();
focusTextInput = () => textInput.current.focus();
return (
<>
<input type="text" ref={textInput} />
<button onClick={focusTextInput}>Focus the text input</button>
</>
);
}
This obviously doesn't work because my svg path elements aren't returned initially. So my question is - how can I achieve this, whether using useRef or not?
Below are some previous questions I looked at which also did not help.
Simulate click event on react element
React Test Renderer Simulating Clicks on Elements
Simulating click on react element
I finally solved it - instead of calling the onClick() which was set inside the node I created a new clickevent with the help of the following code:
function simulateClick() {
let nodelist = d3.selectAll(".unit")
for (let i = 0; i < nodelist._groups[0].length; i++) {
if (nodelist._groups[0].item(i).__data__.properties.filename === currentTargetUnit.properties.filename) {
var event = document.createEvent("SVGEvents");
event.initEvent("click",true,true);
nodelist._groups[0].item(i).dispatchEvent(event);
}
}
}
Related
I have a parent Component which sends a list of data to a List component which in turn sends it to a Label Component to display each data as a label.
I want to be able to focus on the label element when i click on it so that the appropriate style is applied ..
Below is the gist :-
class ContainerComp extends React.Component {
constructor(props) {
super(props);
this.state = {
group: [1, 2, 3]
};
clickHandler = (name, ref) = > {
// I am able to get the DIV as a html element here but calling .focus() on it dosent change the style where as when i explictly add focus using chrome debugger for the element it works.
ref.focus() // not working
}
render() {
return ( <
ListComp group = {
group
}
onClick = {
clickHandler
} >
)
}
}
function ListComp(props) {
const data = props.group.map(... < label onClick = {} > )
return ( <
Label.. >
)
}
function Label(props) {
let ref = createref();
// on focus style for the component is defined in this component
// i am making use of css modules
return ( <
div ref = {
ref
}
onClick = (name, ref) >
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
How can we achieve such a functionality without having to pass a selected prop to the label component ? By default i would select the first element and keep the focus .. or we can make it configurable.
Usually for this I would use Redux and fire off an action which therefore sets the property of the component that needs change, and make a listener that will listen for that specific prop and change style accordingly.
In this situation, id just pass down the event handler to the child component (remember to not call it when you pass it down, so do:
{() => {eventHandler()}}
and then in the child component do:
onClick={this.props.eventHandler(e)}
You will use the event to identify which element triggered it and then apply the class/style/prop to it.
There was some problem with the Ref , I am not quite sure why but i changed it to use the useRef() hook.
Label Component
const elementRef = useRef(null);
return (
<div className={[externalStyle, styles.container].join(' ')} onClick={() => onClickEvent(itemName, elementRef)} ref = {elementRef} tabIndex={1}> // added tabIndex and also changed to useRef
Container Component
clickHandler = (name: string, ref) => {
ref.current.focus(); // volla it worked
}
I tried using the old form of Ref and also useRef() without null previously (el) => (const = el).
It works if some one has some explanation where i went wrong i will be happy to listen as i am able to wrap my head around. may be a nights sleep helped fix it :P
I wanted to create a list of settings that a user can change in the HTML procedurally through javascript.
Much like this: Quality: - 0 +
My approach to this was making an Option class with a value property and prev() and next() methods that change the value within its range. I'm extending this class so it can be a Range, Bool, etc. This is working fine.
My issue is that I can't seem to be able to incorporate this into the HTML. My current solution works only for the last option created, the others don't trigger the onclick event functions, and even if they did I don't feel like this is the right approach to it. How can I make this work in an elegant way?
I have tried the solution shown in this question but it prevents me from accessing the class instance with this.
class UIManager {
constructor (wrapperID, settings) {
this.wrapper = document.getElementById(wrapperID)
this.settings = settings
}
updateUI () {
this.wrapper.innerHTML = ``
for (let id = 0; id < this.settings.options.length; ++id) {
let option = this.settings.options[id]
this.wrapper.innerHTML += `
<li>
<div class="label">
${option.name}
</div>
<div class="option">
<input id="prev${id}" class="open" type="button" value="<">
${option.value}
<input id="next${id}" class="close" type="button" value=">">
</div>
</li>
`
let prevButton = document.getElementById(`prev${id}`)
let nextButton = document.getElementById(`next${id}`)
prevButton.onclick = _ => {
this.settings.options[id].prev()
this.updateUI()
}
nextButton.onclick = _ => {
this.settings.options[id].next()
this.updateUI()
}
}
}
}
The answer to the question you linked as a potential solution is usable so long as you bind the class instance member this to the anonymous function using Function.protoype.bind.
The code would look something like this (using the previously linked answer as the starting point):
for ( var i = 0; i < itemLists.length; i++ ) (function(i){
itemLists[i].onclick = function() {
// do something using `this`
}
}).bind(this)(i);
You mentioned in the comments that this didn't work, but that it was related to overwriting innerHTML and not due to the binding.
Hope this gives a small part of the larger picture.
Try closure to store the values required for functions created from inside the loop.
Something like this :
prevButton.onclick = (function(settings, updateUI) {
return function() {
settings.options[id].prev();
updateUI();
};
})(this.settings, this.updateUI);
nextButton.onclick = (function(settings, updateUI) {
return function() {
settings.options[id].next();
updateUI();
}
})(this.settings, this.updateUI);
I'm playing around with a webapp using React. My code currently creates a list of buttons that can change the color of a circle, depending on the randomly-generated button the user clicks on. To enhance my code, when the user clicks the button, I want all of the buttons colors to change, and therefore need to update all of the button's onClick functions, since they pass their color as an argument to the function that changes the circle's color. Below is the solution I currently have: it requires me to remove every button, and then completely reconstruct the button. Just using button.onclick = function() { newOnclickFunction} does not work, and I have not been able to find the answer on my own. Any help would be greatly appreciated; I'm almost certain there's a better a way to do it than this.
let reflipPalleteCompletely = () => {
let everyButtonPossible = document.getElementsByClassName("colorChangeButton")
for( var button of everyButtonPossible){
button.style.backgroundColor = randomColor()
let myParent = button.parentElement
myParent.removeChild(button)
let freshButton = document.createElement("button", {value: "Click", className: "colorChangeButton", })
freshButton.innerHTML = 'Click'
freshButton.className = 'colorChangeButton'
freshButton.style.backgroundColor = randomColor()
let newOnclickFunction = () => { changeToNewColor(button.style.backgroundColor); reflipPalleteCompletely() }
freshButton.onclick = function() { newOnclickFunction() }
myParent.appendChild(freshButton)
The short answer is: if each button is supposed to change color to reflect the color value it represents, and that set of colors is re-randomized every time a button is pressed, then you can't and shouldn't avoid re-render of the buttons.
However, Mike is right: you're not using React properly if you're writing your own element-creation scripts.
Your component might look like this:
const buttonCount = 10
class Demo extends React.Component {
constructor(props) {
super(props)
this.state = {
currentColor: getRandomColor()
}
}
setColor = (newColor, event) => {
this.setState({
currentColor: newColor
})
}
render() {
let {
currentColor
} = this.props
let colorChoices = Array(buttonCount)
.fill()
.map(() => getRandomColor())
return (
<div className="Demo">
<div className="the-shape" style={{ backgroundColor: currentColor }} />
<ol className="color-choices">
{
colorChoices.map( color => (
<button key={ color }
style={{ backgroundColor: color }}
onClick={ this.setColor.bind(this, color) }
>
{ color }
</button>
))
}
</ol>
</div>
)
}
}
This all depends on you having a getRandomColor function that can generate a color. And it doesn't address making sure that the choices don't include the current color (although you could easily do that by e.g. generating 2n colors, filtering out the currentColor, then taking the first n, or somesuch).
If you really hate redrawing the buttons, you could save their refs and then have the setColor method iterate through them and modify their styles.
But the point of React is to avoid procedural mutation of the DOM in favor of declaring the desired DOM and letting the React engine figure out an efficient mutation strategy.
A direct answer to the question you asked: "what's a more optimal way to change out an HTML element's.onClick element?" might be: find a pattern that doesn't require you to change the function every time.
Instead of having this:
let newOnclickFunction = () => { changeToNewColor(button.style.backgroundColor); reflipPalleteCompletely() }
Try something like this instead:
function onClickButton(event) {
let button = event.target
let color = button.style.backgroundColor
changeToNewColor(color)
}
This way, the desired color value isn't baked into the onClick function. Instead, the function examines the button whose click invoked it, and uses its background as the argument to changeToNewColor.
With some clever CSS, you could write the desired color to a data- prop on each button, and have the browser do the work of calculating background-color from that. Then you could use event delegation on some ancestor element that contains all the buttons, that listens for a click on any element with that data- prop and does the same work as above. This way, you don't even have a click function on each button.
How can I reset an elements 'class' attribute to it's initial value?
I am building a tooltip popup which starts with class="ttPopup". This is then set to the appropriate orientation by adding classes such as class="ttPopup top left".
Problem is when the Popup windows closes, how do I reset the class to it's original value ready for the next time?
There are several ways you could do it:
store in a custom attribute
store in a javascript array
store in localStorage
etc.
Not completely sure if I am correct to use a custom property on the element or not but here is the solution I have used at the moment:
eTooltip.addEventListener("mouseenter", function (oEvent) { ttOpen(oEvent); } );
eTooltip.addEventListener("mouseleave", function (oEvent) { ttClose(oEvent); } );
function ttOpen(oEvent) {
var thisPopup = oEvent.target.getElementsByClassName("ttPopup")[0];
thisPopup.origClassName = thisPopup.className;
}
function ttClose(oEvent) {
var thisPopup = oEvent.target.getElementsByClassName("ttPopup")[0];
if (thisPopup.origClassName) { thisPopup.className = thisPopup.origClassName; thisPopup.origClassName = null; }
console.log(thisPopup.className)
}
Thanks for your help.
In the spec for my app it says (developerified translation): When tabbing to a time element, it should update with the current time before you can change it.
So I have:
<input type="time" ref="myTimeEl" onFocus={this.handleTimeFocus.bind(null, 'myTimeEl')} name="myTimeEl" value={this.model.myTimeEl} id="myTimeEl" onChange={this.changes} />
Also relevant
changes(evt) {
let ch = {};
ch[evt.target.name] = evt.target.value;
this.model.set(ch);
},
handleTimeFocus(elName, event)
{
if (this.model[elName].length === 0) {
let set = {};
set[elName] = moment().format('HH:mm');
this.model.set(set);
}
},
The component will update when the model changes. This works well, except that the input loses focus when tabbing to it (because it gets rerendered).
Please note, if I would use an input type="text" this works out of the box. However I MUST use type="time".
So far I have tried a number of tricks trying to focus back on the element after the re-render but nothing seems to work.
I'm on react 0.14.6
Please help.
For this to work, you would need to:
Add a focusedElement parameter to the components state
In getInitialState(): set this parameter to null
In handleTimeFocus(): set focusElement to 'timeElem` or similar
Add a componentDidUpdate() lifecycle method, where you check if state has focusedElement set, and if so, focus the element - by applying a standard javascript focus() command.
That way, whenever your component updates (this is not needed in initial render), react checks if the element needs focus (by checking state), and if so, gives the element focus.
A solution for savages, but I would rather not
handleTimeFocus(elName, event)
{
if (this.model[elName].length === 0) {
let set = {};
set[elName] = moment().format('HH:mm');
this.model.set(set);
this.forceUpdate(function(){
event.target.select();
});
}
},
try using autoFocus attrribute.
follow the first 3 steps mention by wintvelt.
then in render function check if the element was focused, based on that set the autoFocus attribute to true or false.
example:
render(){
var isTimeFocused = this.state.focusedElement === 'timeElem' ? true : false;
return(
<input type="time" ref="myTimeEl" onFocus={this.handleTimeFocus.bind(null, 'myTimeEl')} name="myTimeEl" value={this.model.myTimeEl} id="myTimeEl" onChange={this.changes} autoFocus={isTimeFocused} />
);
}