Categories
React Answers

How to Update States When Using React State Hook within setInterval

Sometimes, we want to update states when we use React state hook within setInterval.

In this article, we’ll look at how to update states when we use React state hook within setInterval.

Update States When Using React State Hook within setInterval

We can set the state within the setInterval callback to update the state when it’s run.

For instance, we can write:

const App = () => {
  const [count, setCount] = React.useState(0);

  React.useEffect(() => {
    const timer = window.setInterval(() => {
      setCount(count => count + 1)
    }, 1000);

    return () => {
      window.clearInterval(timer);
    };
  }, []);

  return (
    <div>{count}</div>
  );
}

We add the setInterval function into the useEffect callback.

We call setCount inside the callback by passing in a callback that returns the count + 1 .

count is the state that we want to set.

We return a function to clear the timer with clearInterval so that it’s cleared when the component unmounts.

The empty array will ensure that the useEffect callback is run when the component mounts.

Conclusion

We can set the state within the setInterval callback to update the state when it’s run.

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
JavaScript Answers

How to Map Over a JavaScript Object While Preserving the Keys?

We can use the Lodash mapValues method to map property values of a JavaScript object to new values.

For instance, we can write:

const mapped = _.mapValues({
  one: 1,
  two: 2,
  three: 3
}, (v) => {
  return v * 3;
});
console.log(mapped)

We pass in the object we want to transform the property values for as the first argument.

Then we pass in a function to return the mapped value given the property value v ,

Therefore, mapped is:

{one: 3, two: 6, three: 9}

Use the Object.entries and Object.assign Methods

We can use the Object.entries method to get the key-value pairs of an object as an array.

Then we can call map to maps the key-value pair to what we want.

And then we can use Object.assign to create a new object from the key-value pairs.

For instance, we can write:

const obj = {
  one: 1,
  two: 2,
  three: 3
}
const props = Object.entries(obj).map(([k, v]) => ({
  [k]: v * 3
}))
const mapped = Object.assign(...props);
console.log(mapped)

We call Object.entries with obj .

Then we call map to map the v property value to their new values and return an array of objects each with their own key-value pair with the mapped property value.

Next, we spread the props into Object.assign with the props array spread into Object.assign as arguments.

Therefore, mapped is the same as the previous example.