Created
October 12, 2022 14:26
-
-
Save kyle-west/1f2829a355eb3a6caa03696c787f9ad6 to your computer and use it in GitHub Desktop.
Print console.log to the browser in React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result looks like this:
