0

I am trying to create a mud (multi user dungeon) client using Electron and ReactJS for myself for learning and challenging myself. But it seems I failed on this challenge.

I am using telnet-stream to get the data from server.

The data from the server has ansi codes since it's a telnet based communication.

The problem is the speed. I am not sure if I am doing it right but here is the component that is responsible for displaying data:

import React, { Component } from 'react';
import styles from './style.css';

type Props = {
  output: Array<any>
};

export default class ActionWindow extends Component<Props> {
  props: Props;

  componentDidMount() {
    this.scrollToBottom();
  }

  componentDidUpdate() {
    this.scrollToBottom();
  }

  scrollToBottom() {
    this.el.scrollIntoView({ behavior: 'smooth' });
  }

  render() {
    const output = this.props.output.map(chunk => chunk
        .replace('&', '&amp;')
        .replace('<', '&lt;')
        .replace('>', '&gt')
        .replace(/\x1b\[(\d+);(\d+);?(\d+)?m/g, '</span><span class="c-$1 c-$2 x-$3">')
    );
    return (
      <div className={styles.actionWindowWrapper}>
        <span dangerouslySetInnerHTML={{ __html: output }} />
        <div ref={el => { this.el = el; }} />
      </div>
    );
  }
}

Is this the correct way, or there is a faster method? The data comes from the main App component by props.

Valour
  • 773
  • 10
  • 32

1 Answers1

0

Why are you using 'dangerouslySetInnerHTML'? Because you map the output to an html element, you could write:

render() {

return (
  <div className={styles.actionWindowWrapper}>
    this.props.output.map(chunk => chunk
    .replace('&', '&amp;')
    .replace('<', '&lt;')
    .replace('>', '&gt')
    .replace(/\x1b\[(\d+);(\d+);?(\d+)?m/g, '<span></span class="c-$1 c-$2 x-$3">')
    <div ref={el => { this.el = el; }} />
  </div>
);

}

I'm do not completely understand how you regular expresion '.replace(/\x1b[(\d+);(\d+);?(\d+)?m/g, '')' I don't think it outputs correct html because of the closing tag

Stefan van de Vooren
  • 2,524
  • 22
  • 19
  • Because the ansi color codes replacement is like this and for speed purposes, I am posting the output between tags. and without dangerouslySetInnerHTML, It won't process the span tags and will escape the tag. – Valour Mar 04 '18 at 20:00
  • Oké, a comment in this post say that using domElement. innerHTML is faster than dangerouslySetInnerHTML. https://stackoverflow.com/questions/37337289/react-js-set-innerhtml-vs-dangerouslysetinnerhtml Maybe you also win some performance when not using map to iterate over each chunk, but first stringify the output array? In this way you have far less replace calls – Stefan van de Vooren Mar 05 '18 at 10:37