Categories
React Tips

React Tips — Titles, Default Props, and Hooks with Function Components

Spread the love

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.

Render New React Component on Click

We can render a new React component on click if we set a state so that the component can be rendered.

For example, we can write:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showComponent: false,
    };
    this.onClick= this.onClick.bind(this);
  }

  onClick() {
    this.setState({
      showComponent: true,
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.onClick}>click me</button>
        {this.state.showComponent ?
           <Foo /> :
           null
        }
      </div>
    );
  }
}

We have a button that runs the this.onClick method on click.

It changes the showComponent state to true .

Then we can make the Foo component show when this.state.showComponent is true .

Keep document.title Updated in a React App

To make updating the title of a React app easy, we can use the react-document-title package to do it.

To install it, we run:

npm install --save react-document-title

Then we can use it by writing:

function App() {
  return (
    <DocumentTitle title='My App'>
      hello world
    </DocumentTitle>
  );
}

Then ‘My App’ will be the title of our React app.

When we switch components, we can switch the title of the document.

For instance, we can write:

function HomePage() {
  return (
    <DocumentTitle title='Home'>
      <h1>home page.</h1>
    </DocumentTitle>
  );
}

We just wrap our component with the DocumentTitle component to set the title.

It also works with class components:

class NewArticlePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = { title: 'Untitled' };
  }

  render() {
    return (
      <DocumentTitle title={this.state.title}>
        <div>
          <input
            value={this.state.title}
            onChange={(e) => this.setState({ title: e.target.value         })}
          />
        </div>
      </DocumentTitle>
    );
  }
}

We can make the state dynamic by passing in the state variable into the title prop.

It also works with server-side rendered apps.

There’s also the react-helmet plugin which lets us set the page title and more.

To set the title with it, we use the Helmet component with the title element inside.

For instance, we can write:

import React from "react";
import {Helmet} from "react-helmet";

class App extends React.Component {
  render () {
    return (
      <div>
        <Helmet>
          <meta charSet="utf-8" />
          <title>My Title</title>
        </Helmet>
        {/* ... */}
      </div>
    );
  }
};

We can use it to add any element we can add in the head tag, including the title tag.

It also works with both client and server-side rendered apps.

Use React Hooks in a React Classic class Component

To use gooks in a class component, we can create a functional component that’s used as a higher-order component.

For instance, we can write:

const withHook = (Component) => {
  return WrappedComponent = (props) => {
    const someHookValue = useSomeHook();
    return <Component {...props} someHookValue={someHookValue} />;
  }
}

We used our useSomeHook hook in our withHook component.

Then we pass the hooks’s output value into the Component , which can be any component, including a class component.

Then we can use it by writing:

class Foo extends React.Component {
  render(){
    const { someHookValue } = this.props;
    return <div>{someHookValue}</div>;
  }
}

export default withHook(Foo);

We passed in Foo into our withHook higher-order component so that we can use our hook in the withHook HOC.

Call External Javascript Function from React Components

We can call external JavaScript functions from React components.

If we have something like:

<script>
  function test(){
    alert('hello world');
  }
</script>

Then we created a global function that we can call in our React components.

Inside it, we write:

componentWillMount() {
  window.test();
}

Default Prop is not Used when null is Passed

Default props are only set when undefined or nothing is passed in as the value of the prop.

Therefore, if we want to set the default prop value when null is set, we can write:

<Child count={count || undefined} />

If count is falsy, and null is falsy, we’ll pass in undefined as the value of count .

Therefore, the default prop value will be set.

Conclusion

We can render a new component on click if we set a state to make the component render.

document.title can be updated with plain JavaScript or with a package.

We can create higher-order components with hooks if we want to use hooks with a class component.

Default props are only set if the prop is undefined .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *