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.

Categories
React Answers

How to Make React Router Scroll to Top on Every Transition?

Sometimes, we want our React app pages to scroll to the top on every transition.

In this article, we’ll look at how to make our React app pages to scroll to the top on every transition.

React Router Scroll to Top on Every Transition

We can create our own component to scroll to the top and wrap that around the component that we want to scroll to the top.

For instance, we can write:

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollToTop)

We call the withRouter prop with the ScrollToTop component.

Then we have the location prop available in ScrollToTop after that.

In the component, we check the location prop to see what the path is in the componentDidUpdate method.

If they’re different, that means we transitioned to a new route.

So we call window.scrollTo(0, 0) to scroll to the top of the page.

In render , we render the children prop so that we display the content of it.

Then, to use it, we write:

import ScrollToTop from './ScrollToTop';

//...

const App = () => (
  <Router>
    <ScrollToTop>
      <Foo />
    </ScrollToTop>
  </Router>
)

We wrap it our around Foo component to scroll it to the top when it’s loaded.

Also, we can do the same thing with hooks.

For instance, we can write:

import { useEffect } from 'react';
import { withRouter } from 'react-router-dom';

function ScrollToTop({ history }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    }
  }, []);

  return null;
}

export default withRouter(ScrollToTop);

We use withRouter again so that we get the history prop.

But we call history.listen instead of checking the value of history .

We call window.scrollTo(0, 0) whenever the callback of history.listen runs.

It returns a function to remove the listen.

So we put that into the function that’s returned in the useEffect callback.

We pass in an empty array as the 2nd argument of useEffect to only load the callback when the component mounts.

Then we use it by writing:

<Router>
  <>
    <ScrollToTop />
    <Switch>
        <Route path="/" exact component={Home} />
    </Switch>
  </>
</Router>

Conclusion

We can create our own component to scroll to the top and wrap that around the component that we want to scroll to the top.