npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wowblvck/use-iframe

v1.0.8

Published

Two way communication between react components through iframes

Downloads

49

Readme

Use Iframe Hooks

A collection of React Hooks to facilitate communication between iframes and their parents.

If you want to use iframes to embed React-rendered content in your React application, these hooks will help you should you need to communicate with the embedded component.

Installation

npm install --save use-iframe

or

yarn add use-iframe

The library is written in Typescript and ships with it's own type definitions so no additional type defs need to be installed.

Usage

There are three hooks exported by this library:

Here, we are using "parent" to refer to the React component that renders the iframe, and "child" to refer to the React component being used inside the iframe.

You may notice in the examples that handler functions are wrapped in useCallback. This is because when the handler function changes, some tear-down and build-up needs to occur and so to maintain performance you should useCallback to limit the function's reference needlessly changing between renders. To read more about useCallback check out the React documentation

use iframe

Lets say we have a parent component that is rendering an iframe:


// The Parent

import React, { useRef } from 'react';

export const Parent = () => {
  const ref = useRef(null)

  return (
    <div>
      <p>I am the parent component</p>
      <iframe ref={ref} src="/iframe-content" />
    </div>
  )
}

and the child component that is being rendered:


// The Child

import React from 'react';

export const Child = () => {

  return (
    <div>
      <p>I am the child component</p>
    </div>
  )
}

In our parent, we can make use of the useIframe hook to both dispatch messages to the child, and to handle messages from the child:


// The Parent

import React, { useRef, useCallback } from 'react';
import { useIframe } from 'use-iframe';

export const Parent = () => {
  const ref = useRef(null)

  const handler = useCallback(message => {
    switch (message.type) {
      case "child-says":
        console.log(`The child said: ${message.text}`)
    }
  }, [])

  const [dispatch] = useIframe(handler, { ref })

  const onClick = () => dispatch({ type: "parent-says", text: "Hello, Child!" })

  return (
    <div>
      <p>I am the parent component</p>
      <button onClick={onClick}>Parent say message</button>
      <iframe ref={ref} src="/iframe-content" />
    </div>
  )
}

and the child component would look like:


// The Child

import React, { useCallback } from 'react';
import { useIframe } from 'use-iframe';

export const Child = () => {

  const handler = useCallback(message => {
    switch (message.type) {
      case "parent-says":
        console.log(`The parent said: ${message.text}`)
    }
  }, [])

  const [dispatch] = useIframe(handler)
  
  const onClick = () => dispatch({ type: "child-says", text: "Hi, Parent!" })

  return (
    <div>
      <button onClick={onClick}>Child say message</button>
      <p>I am the child component</p>
    </div>
  )
}

Messages can be any JSON-serialisable data, but it's recommended to have a "type" string to help identify what message is being sent and recieved on either end, and you can see in the example above.

Note, that if you are using Typescript then your messages can be declared so you can safely use different message schemas in your handler:


import { useIframe, MessageHandler } from 'use-iframe';

type Message =
  | { type: "text-message", text: string }
  | { type: "other-message", content: string }

const handler: MessageHandler<Message> = useCallback(message => {
  switch (message.type) {
    case "text-message":
      console.log(message.text)
    case "other-message":
      console.log(message.content)
  }
}, [])

const [dispatch] = useIframe<Message>(handler)

The hook knows if it's being rendered in the parent or the child by the presense of the ref being passed into it. If you're writing the parent, pass the ref so the hook knows which iframe to talk to.

use iframe event

This hook is specifically for use with events and event handlers. In our example, lets say there's a button rendered in the iframe (the child) and we want to run a callback in the parent when the button is clicked. It would look like this:


// The Parent

import React, { useRef, useCallback } from 'react';
import { useIframeEvent } from 'use-iframe';

export const Parent = () => {
  const ref = useRef(null)

  const onHelloClicked = useCallback(() => {
    console.log("Someone Clicked Hello!")
  }, [])

  useIframeEvent("hello-btn-clicked", onHelloClicked, { ref })

  return (
    <div>
      <p>I am the parent component</p>
      <iframe ref={ref} src="/iframe-content" />
    </div>
  )
}

// The Child

import React from 'react';
import { useIframeEvent } from 'use-iframe';

export const Child = () => {

  const [onHelloClicked] = useIframeEvent("hello-btn-clicked")

  return (
    <div>
      <p>I am the child component</p>
      <button onClick={onHelloClicked}>Hello</button>
    </div>
  )
}

use iframe shared state

This hook is specifically for sharing some state with the child iframe being rendered by a parent. Both parent and child can mutate state, and it should stay in sync between the two. It is based on the built-in setState React hook.


// The Parent

import React, { useRef, useCallback } from 'react';
import { useIframeSharedState } from 'use-iframe';

export const Parent = () => {
  const ref = useRef(null)

  const [state, setState] = useIframeSharedState({ count: 1 }, { ref });

  const onIncrease = () => setState(state => ({ ...state, count: state.count + 1 }))

  const onDecrease = () => setState(state => ({ ...state, count: state.count - 1 }))

  return (
    <div>
      <p>I am the parent component</p>
      <button onClick={onDecrease}>Decrease</button>
      <button onClick={onIncrease}>Increase</button>
      <iframe ref={ref} src="/iframe-content" />
    </div>
  )
}

// The Child

import React from 'react';
import { useIframeSharedState } from 'use-iframe';

export const Child = () => {

  const [state] = useIframeSharedState({ count: 1 })

  return (
    <div>
      <p>I am the child component</p>
      <p>The count is: {state.count}</p>
    </div>
  )
}

Note that the initial state must be set on both ends, and should be set the same.

Also note, you should only set up ONE piece of shared state per iframe.