Start to using react-vnc to connect wss api (cloud server) on reactjs project
<VncScreen
url='ws://your-vnc-url.com'
scaleViewport
background="#000000"
style={{
width: '75vw',
height: '75vh',
}}
ref={ref}
/>
everything looks good and it connect successfully, but on windows screen of server I need press ctrl+alt+del to unlock, but I don't know how can I do this via react or react-vnc , is there any solution for this?
Is there any way to simulate ctrl+alt+del key on javascript or in react-vnc if not, so how can I press any key on vnc ?
The onConnect, onDisconnect, and onCredentialsRequired callbacks can accept a single parameter rfb. This parameter is the RFB object, which is described by noVNC. Learn more about the RFB object here.
The RFB object should provide a method called sendCtrlAltDel (see API). Maybe you can listen for a specific keypress and call this function instead.
EDIT:
You could receive the RFB object on the 'connect' event and use it later. Then you could create a button on your UI and invoke the rfb.sendCtrlAltDel() function when the button is clicked.
I'm not very familiar with React, but with the following example you might get the idea.
import { VncScreen } from 'react-vnc';
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.rfb;
}
render() {
return (
<VncScreen
url='ws://your-vnc-url.com'
onConnect=(rfb) => this.rfb = rfb
// ...
/>
<button onclick="this.rfb.sendCtrlAltDel()">
CTRL + ALT + DEL
</button>
);
}
}
Edit: Solution for functional component:
import {VncScreen} from "react-vnc";
const ref = useRef();
<VncScreen
url={res.data.wssUrl}
scaleViewport
background="#000000"
rfbOptions={
{
credentials: {
password: res.data.password
}
}
}
onConnect={(rfb) => ref}
style={{
width: '100%',
height: '100vh',
}}
ref={ref}
loadingUI={true}
/>
<Button onClick={()=>ref.rfb.sendCtrlAltDel()}>ctrl+alt+del</Button>
Related
This is my very first app in React. I have created the component and when a user adds text to textArea and clicks on the button, "Download Pdf", I want to pass defaultValue to convertToPdf function.
How do i do that? Basically, I am trying to create a PDF downloader. Any help will be appreciated.
pdfComponent.js
import React, { Component } from "react";
import autosize from "autosize";
import Button from '#material-ui/core/Button';
export class PDFEditorComponent extends Component {
componentDidMount() {
this.textarea.focus();
autosize(this.textarea);
}
convertToPdf() {
this.setState(this.textarea);
console.log("TEXT", this.textarea);
}
render() {
const style = {
maxHeight: "175px",
minHeight: "450px",
minWidth: "800px",
resize: "none",
padding: "9px",
boxSizing: "border-box",
fontSize: "15px"
};
return (
<div>
PDF Downloader
<br />
<br />
<textarea
style={style}
ref={c => (this.textarea = c)}
placeholder="Paste pdf data"
rows={1}
defaultValue=""
/>
<br />
<Button
variant="contained"
color="primary"
onClick={() => this.convertToPdf(this.textarea)}
>
Download Pdf
</Button>
</div>
);
}
}
Bulletpoints:
Actually create a ref for your textarea (in constructor)
constructor(props) {
super(props);
this.textareaRef = React.createRef();
}
then pass it to your textarea element like this
ref={this.textareaRef}
In your convertToPdf() use it like so
this.setState({value: this.textareaRef.current.value})
React state consists of key-value pairs, so you should initialize it in constructor like so
this.state = {
value: null;
}
and then whenever you want to change it (only from within this component), you call setState(), like I did in p. 2
You are mixing html elements with JS variables: you can't call this.textarea, because it's not a variable (nor constant), so remove all such references to it. In React the only way to access DOM elements is by refs (which you already kind of tried, I corrected you in p. 1).
Enjoy React, it's great :)
I am working with react native and I want to pass function and some data from Component class to another Stateless class, but I could not make to passing function and data part.
Here you can see my Component class:
class Classroom extends Component {
constructor(props, context) {
super(props, context);
};
state = {
isLightOn: false,
title : "Turn light on "
}
onPress() {
this.setState({isLightOn: !this.state.isLightOn})
console.log(this.state.isLightOn)
this.setState({title:this.state.isLightOn===false ?"Turn light off":"Turn light on"})
}
render() {
return (
<View style={styles.blue}>
<LightBulb isLightOn={this.state.isLightOn}> </LightBulb>
<LightButton onPress={this.onPress} isLightOn={this.state.isLightOn} title={this.state.title} > </LightButton>
</View>
);
}
}
Firstly, I want to pass isLightOn and title datas to my LightButton class (which mean to my stateless class). After that, I want to use onPress function inside of my Stateless class, but I cannot use. I am taking that error:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
I also LightButton onPress={this.onPress} remove parenthesis, but still taking error.
Here is my my Stateless class
const LightButton = ({onPress,isLightOn,title}) => (
<View style={styles.red}>
<Button
title= {title}
onPress={() => {}
}
/>
</View>
)
I want to use onPress function and datas inside of the this class.
As a result, How can I pass function and data to that class?
The main issue here is that you need to declare onPress using an arrow function or bind it to the component's this value within the constructor. Otherwise it wouldn't have access to the correct this value. Other than that, the way you were passing props into components is perfectly fine.
I also merged your two set state calls in onPress to one as it's easier.
In LightButton, I set it up like this to pass the onPress function down to the button:
const LightButton = ({ onPress, isLightOn, title }) => (
<div style={{backgroundColor:'red'}}>
<Button title={title} onPress={onPress} />
</div>
);
(I set it up using react, but the issues at hand are more of a JS issue than a React/ReactNative one, so the advice should still be valid :) )
const { Component } = React;
const View = 'div';
const Button = (({title,onPress})=><button onClick={onPress}>{title}</button>);
const LightBulb = ({ isLightOn }) => {
return <div className={'LightBulb' + (isLightOn ? ' on' : '')} />;
};
const LightButton = ({ onPress, isLightOn, title }) => (
<div style={{backgroundColor:'red'}}>
<Button title={title} onPress={onPress} />
</div>
);
class Classroom extends Component {
state = {
isLightOn: false,
title: 'Turn light on ',
};
onPress=()=> {
console.log(this.state.isLightOn);
this.setState({
title:
this.state.isLightOn === false ? 'Turn light off' : 'Turn light on',
isLightOn: !this.state.isLightOn
});
}
render() {
return (
<div style={{backgroundColor:'blue'}}>
<LightBulb isLightOn={this.state.isLightOn}> </LightBulb>
<LightButton
onPress={this.onPress}
isLightOn={this.state.isLightOn}
title={this.state.title}
>Button</LightButton>
</div>
);
}
}
ReactDOM.render(<Classroom />, document.querySelector('#root'));
.LightBulb {
height: 50px;
width: 50px;
border-radius: 50px;
background-color: black;
}
.LightBulb.on {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
You can assign it like
const LightButton = ({onPress,isLightOn,title}) => (
...
onPress={onPress}
...
or with an arrow function if you need to pass arg inside
onPress={()=>onPress(someArg)}
do notice that you either don't put () at all, or twice () => func() for not run the function while it is just loads and not clicked.
unrelated directly to your issue but something that you encounter is inside onPress by doing like so
this.setState({isLightOn: !this.state.isLightOn})
console.log(this.state.isLightOn)
this.setState({title:this.state.isLightOn===false ?"Turn light off":"Turn light on"})
setState it is an async call, and therefore second setState usage not guaranteed to refer the state as you expect, use setState({ ... }, () => callback()) or all at one line and accords to prev state
this.setState({isLightOn: !this.state.isLightOn, title: !this.state.isLightOn===false ?"Turn light off":"Turn light on"})
First thing you did wrong is your state instantiating !
you need to instantiate your state in the constructor block like:
constructor(props, context) {
super(props, context);
this.state = { counter: 0 };
}
onPress() you use this for your function which is not recommended in react native or any other language , those are dedicated functions and methods of React Native
For passing a parameter or calling a function it is better to use these patterns ====>
onPress={() => urFunction()} with parenthesis or
onPress={urFunction} without parenthesis
Do the modifications I hope it helps <3
I've followed the documentation and this blog post but I'm struggling to get anything to work.
Locally, I get the following error: HEY, LISTEN! No valid DOM ref found. If you're converting an existing component via posed(Component), you must ensure you're passing the ref to the host DOM node via the React.forwardRef function.
So I've attempted to forward the ref:
class ColorCheckbox extends Component {
setRef = ref => (this.ref = ref);
constructor(props) {
super(props);
}
render() {
const { key, children, color } = this.props;
return (
<button
ref={this.setRef}
key={key}
style={{
...style.box,
background: color,
}}
>
{children}
</button>
);
}
}
export default forwardRef((props, innerRef) => (
<ColorCheckbox ref={innerRef} {...props} />
));
Which is working as I'm able to console.log the ref inside my parent Component:
ColorCheckbox {props: Object, context: Object, refs: Object, updater: Object, setRef: function ()…}
"ref"
However, I still receive the message (above) of No valid DOM ref found....
Here's a simple Codesandbox describing my issue.
About the Codesandbox:
I am getting cross-origin errors in this Sandbox (they do not occur locally). If you change line 14 to be ColorCheckbox the cross-origin error goes...
Any ideas?
When you call forwardRef on a class based component and try to pass the ref through the ref attribute it will not work. The documentation example will only work for regular DOM elements. Rather try doing the following:
export default forwardRef((props, innerRef) => (
<ColorCheckbox forwardRef={innerRef} {...props} />
));
I've just used an arbitrary name, so in this case forwardRef, to pass the ref as a prop. In your class based component I've changed the part where the ref is set on the button to this:
const { key, children, selected, color, forwardRef } = this.props;
return (
<button
ref={forwardRef}
key={key}
style={{
...
The following approach, which they feature in their blog post, will only work for regular DOM elements and styled-components:
const MyComponent = forwardRef((props, ref) => (
<div ref={ref} {...props} />
));
Please refer to my Codesandbox fork to see a working example.
I need help with react app and IconMenu from material-ui.
Studying many similar issues without results :(
Having following code, I want to trigger menu expand manually - I need it in tests framework to simulate clicking on submenu item.
const Menu = () => {
return (
<IconMenu
iconButtonElement={<FlatButton style={{height: '100%'}
}
onClick={() => console.log('clicked!')}
label={'FooLabel'}
labelPosition='before'
/>}>
<MenuItem primaryText="submenu" leftIcon={<SignOutIcon />} />
</IconMenu>
);
};
The problem is that, when I do click on menu item, the onClick event is triggered, but menu is not expanded at all:
demo: https://imgur.com/32RzHcB
I was trying to send custom event by dispatchEvent function, but even onClick is not triggered.
Is something what i missed?
It looks like by using onClick you override the default behaviour, so you'll need to use IconMenu's open prop and tell it when you want it to be open (true) or closed (false).
You'll need to have some code in your component that toggles open between true and false. To do this, the component will need to be stateful instead of functional. If you haven't done this before, check out the react docs on converting a function to a class
Try:
class Menu extends React.Component {
constructor(props) {
super(props);
this.state = {
menuOpen: false
};
}
_toggleOpen = () => {
this.setState({
menuOpen: !this.state.menuOpen
});
};
_handleClick = () => {
this._toggleOpen();
// .. do your other on click stuff here
}
render(
<IconMenu
iconButtonElement={<FlatButton style={{height: '100%'}
}
onClick={this._handleClick}
label={'FooLabel'}
labelPosition='before'
open={this.state.menuOpen}
/>}>
<MenuItem primaryText="submenu" leftIcon={<SignOutIcon />} />
</IconMenu>
);
}
so now we've got a state that the Menu component can update which will decide whether the menu should be open and which gets passed down into the open prop.
I have a blog implementation based on ReactJS that I would like to integrate with AddThis. I have my social icons and I want to use them. So I'm looking for a way to integrate just the AddThis backend service.
I tried looking around but I was not able to find how to integrate AddThis to a ReactJS component.
I saw this somewhere and it uses a special namespace which to the best of my knowledge is not react friendly.
<div addthis:url='blog_url' addthis:title='blog_title' class="addthis_toolbox">
<a class="addthis_button_facebook">
<svg ... />
</a>
<a class="addthis_button_twitter">
<svg ... />
</a>
<a class="addthis_button_linkedin">
<svg ... />
</a>
<a class="addthis_button_reddit">
<svg ... />
</a>
</div>
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#pubid=xa-4fc9383e1ee05f1b"></script>
Also, I saw this JSFiddle with some information on it, but it is not using ReactJS and does not use custom icons.
Question: Is there any good documentation around AddThis + React?
In addition to the data attribute changes you should use the addthis.layers.refresh() method to dynamically refresh/load your AddThis components:
render() {
return (
<div className="addthis_inline_share_toolbox"
data-url={this.props.myurl}
data-title="Check out this URL"
>
</div>
);
}
Then in componentDidMount():
componentDidMount() {
addthis.layers.refresh();
}
EDIT: The above method is the initial approach i took and does initialise the add this widget however, the widget seems to not update the data-url when the prop is changed. even if i call addthis.layers.refresh(); again after a props update
Dynamic update solution:
In my render method:
// Don't use data attributes
<div className="addthis_inline_share_toolbox"></div>
Use the lifecycle methods:
componentDidMount() {
addthis.layers.refresh(); // important! init the add this widget
addthis.update('share', 'url', 'my-initial-url'); // update with initial prop value
}
componentDidUpdate() {
addthis.update('share', 'url', this.props.myurl); // update with prop value
}
componentWillReceiveProps(nextProps) {
addthis.update('share', 'url', nextProps.myurl); // update with prop value
}
Replace addthis:url and addthis:title with data-addthis-url and data-addthis-title.
I put this div in to display the addthis buttons.
<div className="addthis_inline_share_toolbox" data-url={ `http://[Your URL]` } data-title={ `[Your Title]` }></div>
But I also needed to load the javascript after the component mounted or the buttons never display. I assume if you add the javascript to your template that it's loading before the share_toolbox is loaded.
componentDidMount() {
setTimeout( () => {
var addthisScript = document.createElement('script');
addthisScript.setAttribute('src', 'http://s7.addthis.com/js/300/addthis_widget.js#pubid=[your id here]')
if (document.body) document.body.appendChild(addthisScript)
});
},
Here is how I did it:
Please, note that I'm using the inline share toolbox.
Thanks #Mark for addthis.update and to #jvoros for react-load-script
import React, { useEffect } from 'react';
import Script from 'react-load-script';
const AddThis = (props) => {
useEffect(() => {
if (window.addthis) {
window.addthis.update('share', 'url', props.url);
}
}, [props.url]);
const handleAddthisLoaded = () => {
window.addthis.init();
window.addthis.update('share', 'url', props.url);
};
return (
<>
<div className="addthis_inline_share_toolbox"></div>
<Script
url="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-xxxxxxxxxxxxxxxx"
onLoad={handleAddthisLoaded} />
</>
);
}
export default AddThis;
This was the only info I could find on implementing AddThis in a React app. Eventually helped me get a fix. I am posting my solution for anyone else who comes across this.
Using React Router and AddThis presented some challenges. The key was attaching the addThis javascript methods to window events and not React lifecycle events.
I used react-load-script to asynchronously load the script on the main page of my app, and implemented a callback to initialize the addThis widget and then set state to indicate if addThis was loaded. Then that state gets passed down to the component.
Partial code:
import * as LoadScript from 'react-load-script';
class App extends React.Component {
constructor(props) {
this.state = { addThisLoaded: false }
}
handleScriptLoad() {
this.setState({ addthisLoaded: true });
window.addthis.init();
}
render() {
return (
<LoadScript
url="http://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-xxxxxxxxxxxxxxxx"
onLoad={this.handleScriptLoad.bind(this)}
/>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/page/:id"
render={routeProps => (<Page {...routeProps} addThisLoaded={this.state.addThisLoaded} />)}
/>
</Switch>
);
}
}
Then in the component that implements the addThis widget I attached the window event listeners to the React lifecycle hooks. The addThisLoaded prop can be used to conditionally render the widget.
export default class Page extends React.Component<Props> {
componentDidMount() {
window.addEventListener('load', window.addthis.layers.refresh());
}
componentWillUnmount() {
window.removeEventListener('load', window.addthis.layers.refresh);
}
render() {
const page_url = `YOUR URL GOES HERE`;
const page_title = `YOUR TITLE GOES HERE`;
return (
<div>
{this.props.addThisLoaded === true && (
<div className="addthis_inline_share_toolbox" data-url={page_url} data-title={page_title} />
)}
</div>
);
}
}
If there is a better way to handle it I'd love to hear. The AddThis API docs are sparse. And the fact that it manipulates the DOM to get the desired behavior makes it tricky to incorporate with React Router.
Replace addthis:url with data-url