Skip to content

Instantly share code, notes, and snippets.

@kyle-west
Created October 12, 2022 14:26
Show Gist options
  • Save kyle-west/1f2829a355eb3a6caa03696c787f9ad6 to your computer and use it in GitHub Desktop.
Save kyle-west/1f2829a355eb3a6caa03696c787f9ad6 to your computer and use it in GitHub Desktop.
Print console.log to the browser in React
import { useEffect, useState } from 'react'
const _logEntries = new Set()
function log (...args) {
const entry = { args, id: performance.now() }
_logEntries.add(entry)
window.dispatchEvent(new CustomEvent('custom-log', { detail: entry }))
}
const _log = console.log
if (!console.__log_masked) {
console.log = (...args) => {
_log(...args)
log(...args)
}
console.__log_masked = true
}
const ulStyles = {
border: '1px solid grey',
listStyleType: 'disclosure-closed',
fontFamily: 'Consolas, monospace'
}
function render(arg) {
if (arg instanceof HTMLElement) return arg.outerHTML
let stringified = arg.toString()
if (stringified === '[object Object]') {
try {
stringified = JSON.stringify(arg)
} catch (err) {}
}
return stringified
}
function LogEntry ({ args }) {
if (args[0]?.startsWith?.('%c')) {
const style = Object.fromEntries([args[1].split(': ')])
return <li style={style}>{args.slice(2).map(render).join(' ')}</li>
}
return <li>{args.map(render).join(' ')}</li>
}
export function ConsoleInBrowser () {
const [logEntries, setLogEntries] = useState([..._logEntries])
useEffect(() => {
const listener = () => {
setLogEntries([..._logEntries])
}
window.addEventListener('custom-log', listener)
return () => window.removeEventListener('custom-log', listener)
}, [])
function clear() {
setLogEntries([])
_logEntries.clear()
}
return (
<ul style={ulStyles}>
<li style={{ listStyle: 'none', margin: 12 }}>Console.log entries mirrored below: <button onClick={clear}>🗑 clear</button></li>
{logEntries.map(({id, args}) => <LogEntry key={id} args={args}/>)}
</ul>
)
}
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { ConsoleInBrowser } from './console.js'
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
<ConsoleInBrowser />
</React.StrictMode>
);
@kyle-west
Copy link
Author

kyle-west commented Oct 12, 2022

Result looks like this:
Screen Shot 2022-10-12 at 8 28 53 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment