Xterm.js: How to hide xterm-helper-textarea? - javascript

I try to use Xtermjs in Reactjs. but when I follow the guide. the result shows as following:
It should show without top textarea and text 'W'.
My codes is as following:
import React from 'react';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
class XTerminal extends React.Component {
componentDidMount() {
const {id} = this.props;
const terminalContainer = document.getElementById(id);
const terminal = new Terminal({cursorBlink: true});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(terminalContainer);
terminal.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
fitAddon.fit();
}
render() {
return(
<div id={this.props.id}></div>
)
}
}
export default XTerminal;
I seach a similar question in stackoverflow without no answer. and I cannot comment in that question. So I write this question. Could anyone help? thanks :)

Finally I got this. For those who have this problem. you should import xterm css style file. like following:
import React from 'react';
import { Terminal } from 'xterm';
import './xterm.css';
import { FitAddon } from 'xterm-addon-fit';
class XTerminal extends React.Component {
componentDidMount() {
const {id} = this.props;
const terminalContainer = document.getElementById(id);
const terminal = new Terminal({cursorBlink: true});
const fitAddon = new FitAddon();
terminal.loadAddon(fitAddon);
terminal.open(terminalContainer);
terminal.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ');
fitAddon.fit();
}
render() {
return(
<div id={this.props.id}></div>
)
}
}
export default XTerminal;

Related

React HtmlElement Micro Front end is not reloading in Shell Application

I am trying to inject below react mfe into another angular shell application. But, it is loading first time, but when they hide or remove from dom and then again it is not able to load.
Can you please help what is wrong in below code so that they can reload or hide/show properly.
Thanks in advance.
import React, { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import AchPayment from "./AchPayment";
//import createCustomElement from "react-custom-element-builder";
const mount = (el, props) => {
const { consumerName, token, achTransactionRequest } = props;
const root = createRoot(el!);
if (consumerName) {
if (
consumerName.toUpperCase() == "APEX" ||
consumerName.toUpperCase() == "MYFINANCING"
) {
class AchPaymentElement extends HTMLElement {
connectedCallback() {
root.render(
<div>
<AchPayment {...props} />
</div>
);
}
}
customElements.get("ach-payment-element") ||
customElements.define("ach-payment-element", AchPaymentElement);
} else {
return root.render(<h1>Invalid Consumer !</h1>);
}
} else {
return root.render(<h1>Invalid Consumer !</h1>);
}
};
const props = {
consumerName: "MyFinancing",
};
const devRoot = document.querySelector("#_myMfe");
mount(devRoot, props);
i recommend this approach, might help
https://github.com/module-federation/module-federation-examples/tree/master/angular14-react
more documentation you can find here https://webpack.js.org/concepts/module-federation/

Adding React Component child to another React Component at runtime

I am super stuck with ReactJs in trying to add one Virtual Component to another Component at runtime and failing to do so. Here is what I am trying to do:
My App.js looks like this:
import React from 'react';
import './App.css';
// Components
import Header from './components/Header';
import Footer from './components/Footer';
import LeftSideSpace from './components/LeftSideSpace';
import RightSideSpace from './components/RightSideSpace';
import CenterSpace from './components/CenterSpace';
// main class name: App
class App extends React.Component {
// main function name: render
render() {
return (
<div className="App">
<Header title='My Blog'/>
<LeftSideSpace/>
<CenterSpace/>
<RightSideSpace/>
<Footer title='Welcome! This is my Blog site'/>
</div>
);
}
}
export default App;
My focus is on the component <CenterSpace/> which I am importing from here:
import React from 'react';
import PropTypes from 'prop-types'
class CenterSpace extends React.Component {
render() {
return (
<centerspace className="Site.CenterSpace">
<div id="Site.CenterSpace.Content">
{this.props.children}
</div>
</centerspace>
);
}
}
// props defaults
CenterSpace.defaultProps = {
title: 'Personal Blogger\'s site'
}
// props validations
CenterSpace.propTypes = {
title: PropTypes.string.isRequired
}
export default CenterSpace
Then I have a menu component like this, as of now, this is what I have in code, which I am sure contains bugs:
import React from 'react';
import PropTypes from 'prop-types'
import CenterSpace from '../CenterSpace'
import HomeLists from './HomeLists'
class MainMenu extends React.Component {
render() {
return (
<div className="Site.MainMenu">
<button onClick={this.props.onClickHome}>Home</button>
<button onClick={this.props.onClickBlogs}>Blogs</button>
<button onClick={this.props.onClickAboutMe}>About Me</button>
</div>
);
}
}
// props defaults
MainMenu.defaultProps = {
//control button clicks
onClickHome: () => {
var home_dom = new HomeLists();
var center_dom = new CenterSpace<String>("My Blog list");
console.log("say we went to home")
center_dom.appendChild(home_dom);
},
onClickBlogs:() => {
console.log("say we went to blogs")
},
onClickAboutMe:() => {
console.log("say we went to about me")
}
}
// props validations
MainMenu.propTypes = {
onClickHome: PropTypes.func.isRequired,
onClickBlogs: PropTypes.func.isRequired,
onClickAboutMe: PropTypes.func.isRequired,
}
export default MainMenu
This main-menu is used to dynamically add and remove components, but I am failing to do so. When I click Home button, the action I am trying achieveis to add <HomeList/> component to <CenterSpace/>. And futher, <HomeList/> is parsing some Json files and appending as child divs.
<HomeList/> looks like this (may have some issues, was not able to make it work, but that is something I can fix):
import React from 'react';
import PropTypes from 'prop-types'
class HomeLists extends React.Component {
render() {
const fs_obj = require('fs');
const fs_path = require('path');
const fs_jsons = fs_obj.readdirSync('../data').filter(file => fs_path.extname(file) === '.json');
fs_jsons.forEach(file => {
const file_data = fs_obj.readFileSync(fs_path.join('../data', file));
const json = JSON.parse(file_data.toString());
const blog_title = json.title;
var snippet_header = document.createElement('h3');
snippet_header.textContent(blog_title);
const blog_desp = json.blog.content[0].value;
var snippet_text = document.createElement('p');
snippet_text.textContent(blog_desp);
var snippet = document.createElement('div');
snippet.appendChild(snippet_header);
snippet.appendChild(snippet_text);
this.appendChild(snippet);
});
return (
<homelists className="Site.HomeLists">
<div id="Site.HomeLists.Content">{HomeLists}</div>
</homelists>
);
}
}
// props defaults
HomeLists.defaultProps = {
title: 'Personal Blogger\'s site'
}
// props validations
HomeLists.propTypes = {
title: PropTypes.string.isRequired
}
export default HomeLists
Right now when I click Home, all I get is the following error:
TypeError: center_dom.appendChild is not a function
onClickHome
src/components/complications/MainMenu.js:29
28 | console.log("say we went to home")
> 29 | center_dom.appendChild(home_dom);
| ^
30 | },
31 | onClickBlogs:() => {
32 |
console.log("say we went to blogs")
Can anyone help me get unblock from here.
Use the following component as an example for conditional rendering and it is based on your question as well.
import React from "react";
class MainMenu extends React.Component {
constructor(props) {
super(props);
this.state = { isHome: false, isBlogs: false, isAboutMe: false };
// Binding this keyword
this.onClickHome = this.onClickHome.bind(this);
this.onClickBlogs = this.onClickBlogs.bind(this);
this.onClickAboutMe = this.onClickAboutMe.bind(this);
}
onClickHome() {
this.setState({ isHome: true, isBlogs: false, isAboutMe: false });
}
onClickBlogs() {
this.setState({ isHome: false, isBlogs: true, isAboutMe: false });
}
onClickAboutMe() {
this.setState({ isHome: false, isBlogs: false, isAboutMe: true });
}
render() {
return (
<div className="Site.MainMenu">
<button onClick={this.onClickHome}>Home</button>
<button onClick={this.onClickBlogs}>Blogs</button>
<button onClick={this.onClickAboutMe}>About Me</button>
{this.state.isHome && <div>Home view is enabled</div>}
{this.state.isBlogs && <div>Blogs view is enabled</div>}
{this.state.isAboutMe && <div>AboutMe view is enabled</div>}
</div>
);
}
}
export default MainMenu;
Application View
Refer this link for more info on conditional rendering: https://reactjs.org/docs/conditional-rendering.html

what am I doing wrong with useContext?

I am trying to use the useContext from preact. It seems I am doing something wrong, because my Context give undefined values.
Here is the main file:
const {render, h, createContext} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import SampleComp from './sample-comp.js'
export const ContextOne = createContext()
export const ContextTwo = createContext()
const RootComp = (props) => {
return html`
<ContextOne.Provider value=${'ContextOne'}>
<ContextTwo.Provider value=${'ContextTwo'}>
<${SampleComp}/>
</ContextTwo.Provider>
</ContextOne.Provider>
`
}
render(html`<${RootComp} />`, document.body);
and here is the sample component:
const {useContext} = window.preactHooks
const {h} = window.preact
import htm from 'https://unpkg.com/htm?module'
const html = htm.bind(h)
import {ContextOne, ContextTwo} from './index.js'
export default function SampleComp (props) {
const one = useContext(ContextOne)
const two = useContext(ContextTwo)
return html`<div>${one} - ${two}</div>`
}
What am I doing wrong here? I have been trying to figure it out for a few hours now but no idea.
I got it.
Just after posting the question I realized that by using htm I need to wrap the providers in the template string to be a variable. so correct would be:
const RootComp = (props) => {
return html`
<${ContextOne.Provider} value=${'ContextOne'}>
<${ContextTwo.Provider} value=${'ContextTwo'}>
<${SampleComp}/>
</ContextTwo.Provider>
</ContextOne.Provider>
`
}

react native - assigning state to const

I'm starting with react native, and when using a library called react native paper, I've come across a statement where the state is being assigned to a const as shown below.
import * as React from 'react';
import { Searchbar } from 'react-native-paper';
export default class MyComponent extends React.Component {
state = {
firstQuery: '',
};
render() {
const { firstQuery } = this.state;
return (
<Searchbar
placeholder="Search"
onChangeText={query => { this.setState({ firstQuery: query }); }}
value={firstQuery}
/>
);
}
}
Beginning of the 'Render' method, you could see const { firstQuery } = this.state;
Could someone please explain why the state is being assigned to a const named 'firstQuery', and even if it have a reason, how will the assignment correctly map the property 'firstQuery' inside the state object to the const ?
Thanks in advance. The code sample is from https://callstack.github.io/react-native-paper/searchbar.html#value
That syntax is not React nor React Native. It's just Javascript's syntax, called destructuring.
const { firstQuery } = this.state;
is equivalent to
const firstQuery = this.state.firstQuery;
just a short-hand shortcut syntax, you see 2 firstQuerys? People just don't want duplication in code, so they invented it.
See the vanilla javascript snippet below:
const object = {
name: 'Aby',
age: 100,
}
const { name, age } = object;
// instead of
// const name = object.name;
console.log(name, age);
console.log(object.name, object.age);
//=========================================
// imagine:
const obj = {
veryLongPropertyNameToType: 420
}
const { veryLongPropertyNameToType } = obj;
// instead of
// const veryLongPropertyNameToType = obj.veryLongPropertyNameToType;
Like another answer mentioned, it's just JavaScript syntax aka destructuring. If you're feeling confused and wished to just use the "vanilla" JavaScript syntax, you can take a look at below.
import * as React from 'react';
import { Searchbar } from 'react-native-paper';
export default class MyComponent extends React.Component {
state = {
firstQuery: '',
};
render() {
return (
<Searchbar
placeholder="Search"
onChangeText={query => { this.setState({ firstQuery: query }); }}
value={this.state.firstQuery} // <<<<<<<<<<< LOOK HERE
/>
);
}
}

Using 'ref' on React Styled Components is not working

I am having difficulty using refs with Styled Components. When I try to access them in my class methods like below, I get the following error:
Edit.js:42 Uncaught TypeError: this.....contains is not a function
constructor(props) {
....
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
----------
setWrapperRef = (node) => {
this.wrapperRef = node;
}
handleEdit = (e) => {
e.preventDefault();
this.props.onEdit(this.props.id, this.state.title);
}
----------
<Wrapper onSubmit={this.handleEdit} ref={this.setWrapperRef}>
...
</Wrapper>
I found the code from this question
What am I doing wrong here?
I found the answer myself. The solution is to use innerRef instead of ref as the ref itself points to the Styled Component and not the DOM node.
A detailed discussion can be found on GitHub
If you extend another component in styled ref forwarding requires efford. so my solution was extending that component with as prop.
before:
import { useRef } from 'react'
import styled from 'styled-components'
const Card = styled.div``
const Block = styled(Card)``
const Component = () => {
const ref = useRef(null);
return <Card ref={ref} />
}
after:
import { useRef } from 'react'
import styled from 'styled-components'
const Card = styled.div``
const Block = styled.div``
const Component = () => {
const ref = useRef(null);
return <Block as={Card} ref={ref} />
}
const StyledComponent = styled.div.attrs(({ref}) => ({
ref: ref,
}))``
const App = () => {
const anyRef = useRef();
return <StyledComponent ref={anyRef}/>
};

Categories