2

I want to add the onFocus event handler on my element only if a condition is true. Right now, I was hoping to be able to do a ternary on the onFocus itself, so something like this:

<input
  type='text'
  className='some-class'
  value={value}
  onFocus={useTheOnFocus ? evt => onFocusHandler(evt) : null}
  onChange={evt => onChangeHandler(evt.target.value)}
/>

This however, does not work and generates a series of errors and warnings:

Uncaught TypeError: handler.apply is not a function

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

I know the alternative would be to just write the input tag twice within it's own ternary one with the onFocus and the other without it. But I would like to do it in a more condensed matter. Is there another simpler and more condensed way to get this done?

2
  • Instead of null just use () => {}? Commented Jul 17, 2018 at 15:09
  • 1
    Oops! I had completely forgotten. Commented Jul 27, 2018 at 13:27

2 Answers 2

2

you can add this

onFocus={useTheOnFocus ? onFocusHandler : undefined}

or set a handler

onFocus={onFocusHandler}

and check a condition in a handler

onFocusHandler = (ev) => {
   if(!condition) {
      return null;
   }
   // your code
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can give event handlers a value of undefined if you don't want them to be active.

Example

class App extends React.Component {
  state = { useTheOnFocus: false };

  componentDidMount() {
    setInterval(() => {
      this.setState(prevState => ({
        useTheOnFocus: !prevState.useTheOnFocus
      }));
    }, 2000);
  }

  onFocusHandler = evt => {
    evt.preventDefault();
    console.log("Focus handler active");
  };

  render() {
    const { useTheOnFocus } = this.state;

    return (
      <input
        type="text"
        className="some-class"
        onFocus={useTheOnFocus ? this.onFocusHandler : undefined}
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<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="root"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.