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.

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 Use the React useEffect Hook with Debounce?

Sometimes, we may not want to run the code in the useEffect hook immediately after a state update.

In this article, we’ll look at how to use the useEffect hook with the code inside the useEffect callback debounced.

Use the React useEffect Hook with Debounce

We can create our own hook that uses the useEffect hook to run code with the useEffect callback debounced.

To do this, we can write:

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

const useDebounce = (value, delay) => {
  const [debouncedValue, setDebouncedValue] = useState("");
  const firstDebounce = useRef(true);

  useEffect(() => {
    if (value && firstDebounce.current) {
      setDebouncedValue(value);
      firstDebounce.current = false;
      return;
    }

    const handler = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => clearTimeout(handler);
  }, [value, delay]);

return debouncedValue;
};

export default function App() {
  const value = useDebounce("abc", 1000);

  useEffect(() => {
    console.log(value);
  }, [value]);

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

We create the useDebounce hook with the value and delay parameters.

value is the value we want to set.

delay is the denounce delay for the useEffect callback code.

We have the firstDebounce ref to keep track of whether the denounced code is running the first time.

In the useEffect callback, we set firstDebounce.current to false so that we know that it’s not the first time that the denounced code is run it.

Then we call the setTimeout function with a callback with the denounced code.

In the callback, we call setDebouncedValue to set the debouncedValue state value.

Then we return the call that runs clearTimeout which runs when the component is unmounted.

In App , we call useDebounce with the value we want to set and the delay.

Then we log the value in the useEffect callback when the value value changes.

And we also render the value below that.

Now we should see the 'abc' string rendered and logged after 1 second.

Conclusion

We can create our own hook to run code that we want to denounce within the useEffect callback.