Ad

Create An Event On Key Press

- 1 answer

I'm trying to create a component that will fire an event whenever text is entered into the input field. However, it seems like the event only fires when I refresh the page or when I dispatch an event from another component. Even then it only fires the one time.

How can I create a component that only dispatches events when a key is pressed inside the input? How can I make sure that incrementing the Counter component doesn't also fire the onKeyPress event?

// Reducers
const counter = (state = 0, action) => {
    switch (action.type) {
        case 'INCREMENT':
            return state + 1;
        case 'DECREMENT':
            return state - 1;
        default:
            return state;
    }
};


// Store
const reducer = combineReducers(reducers);
const store = createStore(reducer);


// Components
const Counter = ({ value, onIncrement, onDecrement }) => (
    <div>
        <h1>{value}</h1>
        <button onClick={onIncrement}>+</button>
        <button onClick={onDecrement}>-</button>
    </div>
);

class TestComponent extends Component {
    render() {
        return (
            <input onKeyPress={ console.log('key pressed') } />
        );
    };
};


// Render
const render = () => {
  ReactDOM.render(
    <div>
        <Counter
          value={ store.getState().counter }
          onIncrement={ () => store.dispatch({ type: 'INCREMENT' }) }
          onDecrement={ () => store.dispatch({ type: 'DECREMENT' }) }
        />
        <TestComponent />
    </div>,
    document.getElementById('root')
  );
};
store.subscribe(render);
render();
Ad

Answer

Make your onKeyPress value a function. i.e.

<input onKeyPress={(event) => console.log('key pressed', event)} />
Ad
source: stackoverflow.com
Ad