Categories
React Answers

Hoe to Register Event Handlers within the React useEffect Hook?

Sometimes, we want to registrar events listeners within the useEffect hook.

In this article, we’ll look at how to registrar events listeners within the useEffect hook.

Register Event Handlers within the React useEffect Hook

We can register events within the useEffect callback.

For instance, we can write:

const App = () => {
  const [userText, setUserText] = useState('');

  const handleUserKeyPress = useCallback(event => {
    const { key, keyCode } = event;
    if (keyCode === 32) {
      setUserText(prevUserText => `${prevUserText}${key}`);
    }
  }, []);

  useEffect(() => {
    window.addEventListener('keydown', handleUserKeyPress);

    return () => {
      window.removeEventListener('keydown', handleUserKeyPress);
    };
  }, [handleUserKeyPress]);

  return (
    <div>
      <p>{userText}</p>
    </div>
  );
}

We listen to the keypress event on the window.

If we press the space key, then the key code will be registered.

Then we can use that to append the state string with the key text.

We just keep appending the key code to the state string.

Conclusion

We can register events within the useEffect callback.

Categories
React Answers

How to Call External JavaScript Function from React Components?

Sometimes, we want to call external JavaScript functions from React components.

In this article, we’ll look at how to call external JavaScript functions from React components.

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();
}

Conclusion

We can call external JavaScript functions from React components.

Categories
React Answers

How to React Hooks in a React Classic class Component

Sometimes, we want to use React hooks in a React class component.

In this article, we’ll look at how to use React hooks in a React class component.

Use React Hooks in a React Classic class Component

To use hooks 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.

Conclusion

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

Categories
React Answers

How to Update Page Title in a React App?

Oftentimes, we want to update the title of a web page in our React app.

In this article, we’ll look at how to update the title of a web page in our React app.

Update Page Title 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.

Conclusion

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

Categories
React Answers

How to Render New React Component on Click?

Sometimes, we want to render a new React component on click in our React app.

In this article, we’ll look at how to render a new React component on click in our React app.

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 .

Conclusion

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