react-terminal-component icon indicating copy to clipboard operation
react-terminal-component copied to clipboard

How to update prompt with useState hook? How to call the an environment variable from my function? Thanks for looking at my code.

Open shaenr opened this issue 4 years ago • 0 comments

Two related problems:

  1. How to update prompt with useState hook? I need to be able to run setPromptText() somewhere to update the prompt, but... I don't know how since the component doesn't have such a function to do that and I don't know how to extend it if its not a class.

  2. How to call the an environment variable from my function? Look at the buildPrompt function and see the comment where I point out my failing attempt to get the cwd from environment variables in state.

This is my code

import React, { useState } from 'react';

import ReactTerminalStateless, { 
  ReactOutputRenderers 
} from 'react-terminal-component';

import { 
  EmulatorState, 
  getEnvironmentVariable 
} from 'javascript-terminal';

import myTheme from './myTheme';
import Level from './levels/level1/index';

import "./app.css";

// Define Emulator State From Modules
const emulatorState = EmulatorState.create({
  'fs': Level.FS,
  'outputs': Level.Output,
  'history': Level.History,
  'environmentVariables': Level.Env,
  'commandMapping': Level.Commands,
})

const buildPrompt = (state) => {
  const headDelim = "┌──("
  const user = Level.Data.user
  const atChar = "@"
  const host = Level.Data.hostname
  const pathDelim = ")-["

// NOTE: This results in TypeError: Object(...) is not a function so Im not doing this right either.
  const cwd = getEnvironmentVariable(state.getEnvVariables(), 'cwd')        


  const tailDelim = "]\n└─$ "
  return headDelim + user + atChar + host + pathDelim + cwd + tailDelim
}

// Component: App
export default function App() {
  // Declaring State Hooks
  const [input, setInput] = useState('');
  const [emuState, setEmuState] = useState(emulatorState);
  const [promptText, setPromptText] = useState(buildPrompt(emuState))

  return (
    <ReactTerminalStateless
      emulatorState={emuState}
      theme={ myTheme }
      promptSymbol={promptText}
      outputRenderers={ ReactOutputRenderers  }
      inputStr={input}
      onInputChange={( (inp) => setInput(inp) )}
      onStateChange={( (eS) => setEmuState(eS) )}
      clickToFocus 
    />
  );
}

Any tips for a newbie? Thank you.

shaenr avatar Aug 22 '21 06:08 shaenr