Categories
React Answers

How to Distinguish Left and Right Click Events in React?

Sometimes, we want to distinguish left and right click events in React.

In this article, we’ll look at how to distinguish left and right click events in React.

Distinguish Left and Right Click Events in React

To distinguish left and right click events in React, we can set the onClick prop and onContextMenu to handle left click and right click events respectively.

For instance, we write:

import React from "react";

export default function App() {
  const handleClick = (e) => {
    if (e.type === "click") {
      console.log("Left click");
    } else if (e.type === "contextmenu") {
      console.log("Right click");
    }
  };

  return (
    <p onClick={handleClick} onContextMenu={handleClick}>
      click me
    </p>
  );
}

to add the handleClick function to handle both left and right click events.

We check which type of click it is with the e.type propety.

If e.type is 'click', then we left clicked on the p element.

And if it’s 'contextmenu', we did a right click.

We can also use the e.nativeEvent.which property to do the same check.

To do this, we write:

import React from "react";

export default function App() {
  const handleClick = (e) => {
    if (e.nativeEvent.which === 1) {
      console.log("Left click");
    } else if (e.nativeEvent.which === 3) {
      console.log("Right click");
    }
  };

  return (
    <p onClick={handleClick} onContextMenu={handleClick}>
      click me
    </p>
  );
}

If e.nativeEvent.which is 1, then we did a left click.

And if it’s 3, then we did a right click.

Conclusion

To distinguish left and right click events in React, we can set the onClick prop and onContextMenu to handle left click and right click events respectively.

Categories
React Answers

How to Call the useEffect Hook Conditionally with React?

Sometimes, we want to call the useEffect hook conditionally with React.

In this article, we’ll look at how to call the useEffect hook conditionally with React.

Call the useEffect Hook Conditionally with React

To call the useEffect hook conditionally with React, we can check for the condition before running the code in the useEffect callback.

For instance, we write:

import React, { useEffect, useState } from "react";

const wantAnswer = true;

export default function App() {
  const [val, setVal] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const json = await res.json();
    setVal(json.answer);
  };

  useEffect(() => {
    if (!wantAnswer) {
      return;
    }
    getAnswer();
  }, []);

  return <div>{val}</div>;
}

to call getAnswer only when wantAnswer is true in the useEffect callback.

To do that, we check if wantAnswer is false.

And if it is, we use the return statement to stop running the useEffect callback.

Conclusion

To call the useEffect hook conditionally with React, we can check for the condition before running the code in the useEffect callback.

Categories
React Answers

How to Disable Button with React

Sometimes, we want to disable buttons in our React app.

In this article, we’ll look at how to disable buttons in our React app.

Disable Button with React

We can disable a button with React by setting the disabled prop of the button.

For instance, we can write:

<button disabled={!this.state.value} />

We can use it in a component by writing:

class ItemForm extends React.Component {
  constructor() {
    super();
    this.state = { value: '' };
    this.onChange = this.onChange.bind(this);
    this.add = this.add.bind(this);
  }

  add() {
    this.props.addItem(this.state.value);
    this.setState({ value: '' });
  }

  onChange(e) {
    this.setState({ value: e.target.value });
  }

  render() {
    return (
      <div>
        <input
          type="text"
          value={this.state.value}
          onChange={this.onChange}
          placeholder='item name'
        />
        <button
          disabled={!this.state.value}
          onClick={this.add}
        >
          Add
        </button>
      </div>
    );
  }

We pass in the value state to let us enter the data that we want into the input field.

Then we check that in disabled prop of the button.

This way, the button is disabled if we have nothing inputted into the form field.

Conclusion

We can disable a button with React by setting the disabled prop of the button.

Categories
React Answers

How to Send Multipart Form Data with Axios in a React Component?

Sometimes, we want to send multipart form data with Axios in a React component.

In this article, we’ll look at how to send multipart form data with Axios in a React component.

Send Multipart Form Data with Axios in a React Component

We can send form data with the FormData constructor.

We can pass that straight into the Axios post method.

For instance, we can write:

import React from 'react'
import axios, { post } from 'axios';

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state ={
      file:null
    }
    this.onFormSubmit = this.onFormSubmit.bind(this)
    this.onChange = this.onChange.bind(this)
    this.fileUpload = this.fileUpload.bind(this)
  }

  onFormSubmit(e){
    e.preventDefault()
    const url = 'http://example.com/upload';
    const formData = new FormData();
    formData.append('file', this.state.file);
    const config = {
      headers: {
        'content-type': 'multipart/form-data'
      }
    }
    post(url, formData, config);
      .then((response) => {
        console.log(response.data);
      })
  }

  onChange(e) {
    this.setState({ file: e.target.files[0 ]})
  }

  render() {
    return (
      <form onSubmit={this.onFormSubmit}>
        <h1>File Upload</h1>
        <input type="file" onChange={this.onChange} />
        <button type="submit">Upload</button>
      </form>
   )
  }
}

We have a file input, where we set the file input to the file that’s submitted in the onChange method.

We save the selected file object as the value of the file state.

Then when we click the Upload button, onFormSubmit is run.

In the method, we created a FomrData instance.

Then we append our file into the FormData instance.

We also set the header so that we indicate that we’re sending form data.

Once we did that, we proceed with our file upload.

Conclusion

We can send form data with the FormData constructor.

We can pass that straight into the Axios post method.

Categories
React Answers

How to Add Custom HTML Attributes in JSX in a React App?

Sometimes, we want to add custom HTML attributes in our React JSX code.

In this article, we’ll look at how to add custom HTML attributes in our React JSX code.

How to Add Custom HTML Attributes in JSX

With React 16, we can add custom attributes natively.

For instance, we can write:

render() {
  return (
    <div data-foo="bar" />
  );
}

We can just add it straight into our HTML elements without doing anything special.

Use Children with React Stateless Functional Component in TypeScript

We can pass in the interface or type alias into the generic type argument of React.FunctionComponent to set the type for ur props.

As long as the alias or interface has the children prop, we can use the children prop.

For instance, we can write:

const Foo: React.FunctionComponent<FooProps> = props => (
  <div>
    <p>{props.bar}</p>
    <p>{props.children}</p>
  </div>
);

FooProps has the bar and children entries, so we can reference both in our component.

React.FC is the shorthand for React.FunctionComponent .

Before React 16.8, we use the React.StatelessComponent type instead.

For instance, we can write:

const Foo: React.StatelessComponent<{}> = props => (
  <div>{props.children}</div>
);

or:

const Foo : React.StatelessComponent<FooProps> = props => (
  <div>
    <p>{props.propInMyProps}</p>
    <p>{props.children}</p>
  </div>
);

React.SFC is the shorthand for React.StatelessComponent.

Conclusion

With React 16, we can add custom attributes natively.