Categories
React Tips

React Tips — Error Handling, Input Validation, and More

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Pass Props Without Value to Component

We can pass boolean props without a value to a component if its value is true .

For instance, we can write:

<input type="button" disabled />;

instead of:

<input type="button" disabled={true} />;

They’re the same.

Access Child Component Functions via Refs

We can assign a ref to a component in a class component to access its methods.

For instance, we can write:

class App extends React.Component {
  save() {
    this.refs.content.getWrappedInstance().save();
  }

  render() {
    return (
      <Dialog action={this.save.bind(this)}>
        <Content ref="content"/>
      </Dialog>);
   }
}

class Content extends React.Component {
  save() {
    //...
  }
}

We have the App component that has the Content that has a ref assigned to it.

Then we can get the component instance with getWrapperdInstance .

And we can call the save method with that.

getDerivedStateFromError and componentDidCatch

Both are methods that let us handle errors in a class component.

getDerivedStateFromError is a static method that lets us set a state when an error occurs.

componentDidCatch lets us commit side effects and access this , which is the component instance.

For instance, we can write:

class ErrorBoundary extends React.Component {
  state = { hasError: false };

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.log(error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h1>error.</h1>;
    }

    return this.props.children;
  }
}

We have the static getDerivedStateFromError method to access the error parameter.

Then we can return something which is the state that’s rendered with the next render.

componentDidCatch lets us access the component instance.

It also has the error and info parameters with more error data.

getDerivedStateFromError works with server-side rendering.

This is because it’s a render phase lifecycle, which is available on server-side rendered apps.

Allow File Input to Select the Same File in React Component

We can let a file input select the same file in a React component if we set it to null after we click on it.

For instance, we can write:

<input
  id="upload"
  ref="upload"
  type="file"
  accept="image/*"
  onChange={(event)=> {
    this.readFile(event)
  }}
  onClick={(event)=> {
    event.target.value = null
  }}
/>

We have the onChange prop that takes a function to read a file.

In the onClick prop, we set the file input value to null .

Passing a Number to a Component

We can pass a number to a component by passing in a number in curly brackets.

For instance, we can write:

Rectangle width={10} height={20} />

Using the Same Component for Different Route path in React Router

We can use the same component for different routes by passing in an array into the path prop.

So we can write:

<Route exact path={["/add", "/edit"]}>
  <User />
</Route>

Conditional Validation in Yup

We can validate a field conditionality with Yup by using the when method.

For instance, we can write:

validationSchema={yup.object().shape({
  showName: yup.boolean(),
  name: yup
    .string()
    .when("showName", {
      is: true,
      then: yup.string().required("name is required")
    })
  })
}

We have the showName boolean field.

And we only validate the name field when it’s true as indicated in the is field.

then lets us do the validation only when showName is true .

Then we return the 'name is required' message if it is.

Fix ‘ Failed form propType: You provided a checked prop to a form field without an onChange handler.’ Warning

To fix this warning, we can add the checked prop with a value if we’re creating a controller component.

For instance, we can write:

<input
  type="checkbox"
  checked={this.props.checked}
  onChange={this.onChange}
/>

If it’s an uncontrolled component, we can write populate the defaultChecked prop:

<input
  type="checkbox"
  defaultChecked={this.props.checked}
/>

Only Allow Numbers to be Inputted in React

We can set the pattern attribute to the regex string we want for restricting the input to numbers.

For instance, we can write:

<input type="text" pattern="[0-9]*" onInput={this.handleChange.bind(this)} value={this.state.goal} />

We specified the pattern and we listen to the inpurt pro.

Then in the handleChange method, we can write:

handleChange(evt) {
  const goal = (evt.target.validity.valid) ?
  evt.target.value : this.state.goal;
  this.setState({ goal });
}

We only set the state if it’s valid, then we won’t get any invalid input in the state.

Conclusion

We can check for input validity in the input handler.

Also, we don’t have to pass in true explicitly into a prop.

Error boundary components have special hooks that we can run code when errors occur.

Categories
React Tips

React Tips — Dispatch and Navigate, useCallback, and Cleanup

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

React.useState does not Reload State from Props

React.useState doesn’t reload state from props.

It can only set the initial state.

If we need to update the state as props change, then we need to use the useEffect hook.

For instance, we can write:

function Avatar({ username }) {
  const [name, setName] = React.useState(username);

  React.useEffect(() => {
    setName(name);
  }, [username])

  return <img src={`${name}.png`}/>
}

We get the username prop .

And we set it as the initial value of the name state with useState .

Then we use the useEffect hook to watch for changes in the name value.

We watch it for changes, then call setName to set the name with the latest value of username as the name ‘s new value.

Then we can use name in the JSX we render.

Use for useCallback

We can use useCallback to cache the callback so that we don’t call a create a new instance of the callback function on every render.

For instance, instead of writing:

function Foo() {
  const handleClick = () => {
    console.log('clicked');
  }
  <button onClick={handleClick}>click me</button>;
}

We write:

function Foo() {
  const memoizedHandleClick = useCallback(
    () => console.log('clicked'), [],
  );

  return <Button onClick={memoizedHandleClick}>Click Me</Button>;
}

The useCallback hook caches the click callback so that the same instance is used on every render instead of creating a new one.

Detect a React Component vs. a React Element

We can check if an object is a function component by checking that it’s a function and that it contains the 'return React.createElement' code.

For instance, we can write:

const isFunctionComponent = (component) => {
  return (
    typeof component === 'function' &&
    String(component).includes('return React.createElement')
  )
}

To check for a class component we can check for type 'function' .

And we can check for the isReactComponent property in the component’s prototype .

For example, we can write:

const isClassComponent = (component) => {
  return (
    typeof component === 'function' &&
    !!component.prototype.isReactComponent
  )
}

To check if a variable is a valid element, we can use the React.isValidElement method to do that.

For example, we can write:

const isElement = (element) => {
  return React.isValidElement(element);
}

React Hooks useEffect() Cleanup When Component Unmounts

We can return a function in the useEffect callback to return a function that runs our clean up code.

For example, we can write:

const { useState, useEffect } = React;

const ForExample = () => {
  const [name, setName] = useState("");
  const [username, setUsername] = useState("");

  useEffect(
    () => {
      console.log("do something");
    },
    [username]
  );

  useEffect(() => {
    return () => {
      console.log("cleaned up");
    };
  }, []);

  const handleName = e => {
    const { value } = e.target;
    setName(value);
  };

  const handleUsername = e => {
    const { value } = e.target;
    setUsername(value);
  };

  return (
    <div>
      <div>
        <input value={name} onChange={handleName} />
        <input value={username} onChange={handleUsername} />
      </div>
    </div>
  );
};

We have our change event handlers.

And we have our useEffect calls.

They all have their own callbacks.

The first one watches for changes in the username function.

In the 2nd one, the callback returns a function that runs code when the component unmounts.

React Router Redirect after Redux Action

We can redirect after a Redux action is committed.

To do that, we install the history package.

We install it by running:

npm install --save history

Then we can create a function like:

import { createBrowserHistory } from 'history';

const browserHistory = createBrowserHistory();

const actionName = () => (dispatch) => {
  axios
    .post('url', { body })
    .then(response => {
       dispatch({
         type: ACTION_TYPE_NAME,
         payload: payload
       });
       browserHistory.push('/foo');
    })
    .catch(err => {
      // Process error code
    });
  });
};

We make a POST request with Axios.

Then in the then callback, we call dispatch to dispatch our actions.

And then we call browserHistory.push to navigate.

We called createBrowserHistory to get the browserHistory object.

Conclusion

We use the useEffect hook to update our values.

It can also be used to run clean up code when a component unmounts.

If we need to navigate to another route after a Redux action is done, we can use the browserHistory.push method to do that after we dispatched our action.

Categories
React Tips

React Tips — Disabling Links, Portals, and Pass Props to Components Passed in as Props

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

How to Disable an <Link> if it’s Active

We can disable a link by setting the pointer-events attribute in our CSS.

Since we can pass a className attribute with the CSS class to the Link , we can write:

class Foo extends React.Component {
  render() {
    return (
      <Link to='/bar' className='disabled-link'>click me</Link>
    );
  }
}

We have the disabled-link class name applied to the link.

Then we can add the following CSS to disable the link:

.disabled-link {
  pointer-events: none;
}

How to Use ReactDOM.createPortal()

We can use the ReactDOM.createPortal() to render a component in an element outside of the usual location in the DOM tree,

For instance, given the following HTML:

<html>
  <body>
    <div id="root"></div>
    <div id="portal"></div>
  </body>
</html>

We can write:

const mainContainer = document.getElementById('root');
const portalContainer = document.getElementById('portal');

class Foo extends React.Component {
  render() {
     return (
       <h1>I am rendered through a Portal.</h1>
     );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
         <h1>Hello World</h1>
         {ReactDOM.createPortal(<Foo />, portalContainer)}
     </div>
    );
  }
}

ReactDOM.render(<App/>, mainContainer);

In App , we called ReactDOM.createPortal(<Foo />, portal to render the Foo component in the portalContainer , which is the div with ID portal in the HTML.

The rest of the JSX code is rendered in their usual places.

This lets us render our components in whatever way we like.

Event Bubbling Through Nested Components in React

React supports synthetic events in both the capturing and bubbling phases.

Therefore, our click events are propagated to the parent elements unless we stop them from doing so explicitly.

So if we have:

<root>
  <div onClick={this.handleAllClickEvents}>
    <foo>
      <bar>
        <target />
      </bar>
    </foo>
  </div>
</root>

We can listen to click events from child component with the handleAllClickEvents method.

Within it, we can write:

handleAllClickEvents(event) {
  const target = event.relatedTarget;
  const targetId = target.id;
  switch(targetId) {
    case 'foo':
      //...
    case 'bar':
      //...
  }
}

We get the click target with the event.relatedTarget property.

Then we get the click target’s ID with the id property.

Then we can check the IDs as we wish.

Difference Ways to Set the Initial State in a React Class Component

There’re multiple ways to set the initial state of a component in a class.

One way is standard and the other isn’t.

The standard way would be:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: 'james'
    }
  }

  render() {
    return  <div>{this.state.name}</div>
  }
}

We set it in the constructor with the this.state assignment.

The non-standard way is:

class App extends Component {
  state = {
    name: 'John'
  }

  render() {
    return  <div>{this.state.name}</div>
  }
}

This isn’t standard JavaScript syntax.

However, we can use it with TypeScript or a Babel plugin to transform it back to standard JavaScript.

This also sets the this.state instance variable.

Pass Props to a Component Passed as a Prop

If we want to pass props to a component that has been passed in as a prop, then we need to clone with the React.cloneElement method.

For instance, we can write:

const GrandChild = props => <div>{props.count}</div>;

class Child extends React.Component{
  constructor(){
    super();
    this.state = { count: 1 };
    this.updateCount= this.updateCount.bind(this);
  }

  updateCount(){
    this.setState(prevState => ({ count: prevState.count + 1 }))
  }

  render(){
    const Comp = this.props.comp;
    return (
      <div>
        {React.cloneElement(Comp, { count: this.state.count })}
        <button onClick={this.updateCount}>+</button>
      </div>
    );
  }
}

class Parent extends React.Component{
  render() {
    return(
      <Child comp={<GrandChild />} />
    )
  }
}

We have the GrandChild component which displays the count prop.

Then we have the Child prop to let us update the count state.

We pass that into the component that’s been passed in from the comp prop with React.cloneElement .

We got to clone it so that we return a version of the component that’s writable.

The 2nd argument has the prop name and value that we want to pass in respectively.

Conclusion

We can pass in props to a component that’s been passed in as a prop with the cloneElement method.

With portals, we can render our component anywhere we like.

And we can disable React Router links with CSS.

Categories
React Tips

React Tips — Disable Buttons, FormData, Types for Function

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

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.

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.

Cannot Read Property ‘map’ of Undefined

We may get this if we try to call map on something that doesn’t have a map method.

This may happen to something that we expect to be an array, but it’s not.

Therefore, we should check if the value we’re calling map on is an array before doing anything.

For instance, we can do that by writing:

if (Array.isArray(this.props.data)) {
  const commentNodes = this.props.data.map((comment) => {
    return (
      <div>
        <h1>{comment.title}</h1>
      </div>
    );
  });
}

We called Array.isArray to check if this.props.data is an array.

If it is, then we call map to map the data prop to h1 elements.

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

We can add types to stateless components with TypeScript.

Sending multipart form data can be done with the FormData constructor.

Also, we should make sure that we have an array before calling map on it.

We can conditionally disable buttons with React.

Categories
React Tips

React Tips — colspan, Active Links, API Calls, and Multiple Refs

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Make API Call with Hooks in React

We can make API calls in the useEffect hook.

For instance, we can write:

function User() {
  const [firstName, setFirstName] = React.useState();

  React.useEffect(() => {
    fetch('https://randomuser.me/api/')
      .then(results => results.json())
      .then(data => {
        const {name} = data.results[0];
        setFirstName(name.first);
      });
  }, []);

  return (
    <div>
      Name: {firstName}
    </div>
  );
}

We get call fetch in the useEffect callback to get the data.

Then we set the firstNam,e state with setFirstName .

We pass in an empty array to the 2nd argument of useEffect to make the callback run on component mount only.

Finally, we render the firstName in the return statement.

If we want to load data when props change, then we pass the prop into the array in the 2nd argument.

React colspan

We can add the colspan attribute with the colSpan prop.

For instance, we can write:

<td colSpan={6} />

How can I Style Active Link in React Router

We can style an active link with React Router with the NavLink component.

For instance, we can write:

<NavLink to="/profile" activeClassName="selected">
  profile
</NavLink>

The activeClassName lets us set the class name for the when the link is active.

There’s also the activeStyle prop to let us pass in styles for active links.

For instance, we can write:

<NavLink
  to="/profile"
  activeStyle={{
    fontWeight: "bold",
    color: "green"
  }}
>
  profile
</NavLink>

We pass in an object with the styles we want to apply.

The CSS property names are all changed to camel case.

Trigger onChange if Input Value is Changing by State

We can set the state in the handler.

And we can trigger the event we want with the Event constructor.

For instance, we can write:

class App extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      value: 'foo'
    }
  }

  handleChange (e) {
    console.log('changed')
  }

  handleClick () {
    this.setState({ value: 'something' })
    const event = new Event('input', { bubbles: true });
    this.input.dispatchEvent(event);
  }
  render () {
    return (
      <div>
        <input readOnly value={this.state.value} onChange={(e) => this.handleChange(e)} ref={(input)=> this.input = input} />
        <button onClick={this.handleClick.bind(this)}>update input</button>
      </div>
    )
  }
}

We have a button that has a click handler attached to it.

That’s the handleClick method.

Then we call setState on it to set the value state.

We then create an input event and make it bubble.

Then trigger an event on the input with dispatchEvent .

Add Google Sign-in Button with React

We can add a Google sign-in button within a React component by loading the google sign-in code in when the component loads.

For instance, we can write:

componentDidMount() {
  gapi.signin2.render('g-signin2', {
    'scope': 'https://www.googleapis.com/auth/plus.login',
    'width': 200,
    'height': 50,
    'longtitle': true,
    'theme': 'dark',
    'onsuccess': this. onSignIn
  });
}

We call the gapi.signin2.render method that comes with the API.

It’s added to componentDidMount so that it runs when the component loads.

With function components, we can write:

useEffect(() => {
  window.gapi.signin2.render('g-signin2', {
    'scope': 'https://www.googleapis.com/auth/plus.login',
    'width': 200,
    'height': 50,
    'longtitle': true,
    'theme': 'dark',
    'onsuccess': onSignIn
  })
}, [])

We call the same method within the useEffect callback.

The empty array in the 2nd argument ensures that it loads only when the component loads.

Use Multiple refs for an Array of Elements with Hooks

We can create multiple refs within the useEffect callback.

For instance, we can write:

const List = ({ arr }) => {
  const arrLength = arr.length;
  const [elRefs, setElRefs] = React.useState([]);

  React.useEffect(() => {
    setElRefs(elRefs => (
      Array(arrLength).fill().map((_, i) => elRefs[i] || ReactcreateRef())
    ));
  }, [arrLength]);

  return (
    <div>
      {arr.map((el, i) => (
        <div ref={elRefs[i]}>...</div>
      ))}
    </div>
  );
}

We have the useState hook to create an array.

Then we call the setElRefs returned from useState to and call fill to create an array with empty slots.

Then we call map to create the refs or return an existing one.

Then we pass the ref by index to the div.

Conclusion

We can add multiple refs by mapping them to the array.

Also, we can make API calls in the useEffect callback.

NavLink s can be styled when they’re active.