How to Manually Trigger Click Event in Reactjs

How to manually trigger click event in ReactJS?

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

In your render method:

<input ref={input => this.inputElement = input} ... />

In your event handler:

this.inputElement.click();

Full example:

class MyComponent extends React.Component {
render() {
return (
<div onClick={this.handleClick}>
<input ref={input => this.inputElement = input} />
</div>
);
}

handleClick = (e) => {
this.inputElement.click();
}
}

Note the ES6 arrow function that provides the correct lexical scope for this in the callback. Also note, that the object you acquire this way is an object akin to what you would acquire using document.getElementById, i.e. the actual DOM-node.

Simulate click event on react element

Use refs to get the element in the callback function and trigger a click using click() function.

class Example extends React.Component{  simulateClick(e) {    e.click()  }  render(){    return <div className="UFIInputContainer"    ref={this.simulateClick} onClick={()=> console.log('clicked')}>      hello      </div>  }}
ReactDOM.render(<Example/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="app"></div>

How can I trigger a click event for a React component using his id?

You can use onFocusChange prop in SingleDatePicker based on this link:

http://github.com/airbnb/react-dates/issues/639

How to manually trigger a click event on a dom in reactjs

I tried both your examples, and the <input> element's .click() method is indeed called. The reason it's not working as you expect is that it the click only puts the keyboard focus in the element, it does not click the date picker. Opening the date picker programmatically is currently not possible, at least not in all browsers.

How do I trigger a click event based on a specific className in ReactJS

I see two possible ways:

  • instead of addItem(), create two separated functions where for 0,5kg onClick action only item.price will be in use and second function for 1kg where you use item.price2

or

  • add second parameter to the addItem() function so it will be possible to differ which price you should use in particular action, like:
const addItem = (item, priceType) => {
switch (priceType) {
case 'price':
// 0,5kg
case 'price2':
// 1kg
default: //default case
}
}

...
<div>
<CustomButton
...
onClick={() => addItem(item, 'price')}
>
Add 1/2kg
</ CustomButton>
<CustomButton
...
onClick={() => addItem(item, 'price2')}
>
Add 1kg
</ CustomButton>
</div>



REDUX

I suggest you to use method no.1 without anti pattern. I have also added method no.2 where I keep the original author way of thinking.

METHOD 1. WITHOUT ANTI PATTERN

  1. In React CollectionItem component use mapStateToProps so you'll get cartItems as a props from the STORE.
  2. Rewrite function triggered onClick event so it do all necessary changes with cartItems and then return updated cartItems list in action.
  3. Reducer just take updated argument and pass it down to the STORE, without any mutations.
const CollectionItem = ({ item, addItem, cartItems }) => {
const { name, price, price2, imageUrl } = item;

const addItemToList = (item, priceType) => {
// addItemToCart() logic
// cartItems argument is available as a props from STORE
addItem(updatedCartItems); //call action
}
return (
...

<CustomButton
...
onClick={() => addItemToList(item, 'price')}
>
Add 1/2kg
</ CustomButton>
)
}

const mapStateToProps = (state) => ({
cartItems: state.cartItems
});
const mapDispatchToProps = (dispatch) => ({
addItem: (updatedCartItems) => dispatch(addItem(updatedCartItems)),
});
export default connect(mapStateToProps, mapDispatchToProps)(CollectionItem);

Action creator

export const addItem = (updatedItems) => ({
type: CartActionTypes.ADD_ITEMS,
payload: updatedItems,
});

Reducer

case CartActionTypes.ADD_ITEMS:
return {
...state,
cartItems: action.payload, // PURE REDUCER
};

METHOD 2. ANTI PATTERN in reducer

As you updated addItem(item, 'price') so it receives two parameters, now it's time to update your action creator and reducer so it will be able to accept second parameter 'price' or 'price2'.

Action Creator - added priceType

export const addItem = (item, priceType) => ({
type: CartActionTypes.ADD_ITEMS,
payload: item,
priceType
});

Reducer - pass down the priceType

CAUTION! Using addItemToCart() inside reducer is anti pattern. According to the redux documentation you should never mutate arguments inside reducer, it should stay pure.

case CartActionTypes.ADD_ITEMS:
return {
...state,
cartItems: addItemToCart(state.cartItems, action.payload, action.priceType),
};

Then addItemToCart(cartItems, cartItemToAdd, priceType) can use switch(priceType) so it will differ price type.

How to create a ref and manually trigger onclick on a textfield in React hooks

You cannot simply assign a ref prop to the TextField and call it a day like what the other answers have described. ref only works on DOM elements such as <input/>. In a custom component you would normally need to use Forwarded Refs.

However, in your case, since you are using MUI TextField, they already expose a prop that enables you to attach the ref to its internal input element. The prop is inputRef.

function App() {

const txtField = React.useRef(null);

return(
<div>
<Button
variant="contained"
color="primary"
onClick={() => {
txtField.current.focus()
// at this point if you need to trigger click then invoke .click() instead
}}>
focus on text field
</Button>

<br/>

<TextField inputRef={txtField} />
</div>
);
}

ReactDOM.render(<App/>, document.getElementById("root"));
<body>
<div id="root"></div>

<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<script type="text/babel">
const { TextField, Button } = MaterialUI;
</script>
</body>

Automatically trigger an OnClick event of a specific component in React

You need the child component to be able to see and do something with the parent's game_logic.tile_values. While it'd be possible to pass the values down from the parent and try to do something with them there, it'd be easier to put the click handlers in the parent so everything can be accessed from there easily.

You'll also need to change around the way you handle state. Having each individual component have its own state will make cross-component communication very difficult, but that's what you need in order for the change in one component (tile) to affect other tiles. Put the state of whether a tile's been revealed or not in the parent.

class Board extends React.Component {
constructor(props) {
super(props);
game_logic.initalizeGame(8,8,10);
game_logic.createGame();
this.state = {
height: 8,
width: 8,
num_mines: 10,
revealed: Array.from(
{ length: 8 },
() => new Array(8).fill(false)
);
}
}
handleReveal = (x, y, visited = new Set()) => {
const tileKey = x + '_' + y;
// if out of bounds, or if visited before, don't do anything
if (visited.has(tileKey) || game_logic.tile_values[x]?.[y] === undefined) return;
visited.add(tileKey);
const isZero = game_logic.tile_values[x][y] === 0;
this.setState({
...this.state,
revealed: this.state.map(
(row, i) => i !== x
? row
: row.map(
(tileState, j) => y === j ? true : tileState
)
)
});
if (isZero) {
handleReveal(x - 1, y);
handleReveal(x + 1, y);
handleReveal(x, y - 1);
handleReveal(x, y + 1);
}
};

Now that the parent component has handleReveal, pass it down to each tile. When there's a left click, call the passed down handleReveal, and have the children tiles decide what image to render by checking whether the parent's revealed state for that X and Y is true or false.

The Tiles probably shouldn't have state themselves except for whether they've been flagged or not. The imgSrc can be determined directly from the props, as can the value. Better not to duplicate state over both parents and children - doing it that way makes things messy and hard to deal with, especially when it comes to updates.



Related Topics



Leave a reply



Submit