I use Cytoscape.js with create-react-app. The terminal is running the app but is not outputting console.log. Especially in the handleClick method.
import React, { Component } from 'react'
import Cs from 'cytoscape'
const { cyConfig, cyStyle } = require('./config/config')
class Graph extends Component {
componentDidMount () {
cyConfig.container = document.getElementById('cy')
this.cy = Cs(cyConfig)
}
handleClick () {
this.cy.on('tap', 'node', (e) => {
const node = e.target
console.log(node.id())
})
}
render() {
return (
<div
style={cyStyle}
id='cy'
onClick={ (e) => this.handleClick(e) }
/>
)
}
}
export default Graph
Related
App
import React from 'react'
import MyComponent from './MyComponent'
import {ConnectionProvider from './context'
const App extends React.Component {
render() {
return (
<ConnectionProvider>
<MyComponent />
</ConnectionProvider>
)
}
}
export default App
Context
import React, { createContext, useState } from 'react'
import { Connection } from '#web/_types'
import { ContactService } from '#web/_services'
interface IConnectionContextData {
connections: Connection[]
getConnections: () => void
connect: (
contactId: string,
source: string,
) => void
}
const ConnectionContextDefaultValue: IConnectionContextData = {
connections: []
getConnections: () => null,
connect: () => null,
}
const useConnectionContextValue = (): ConnectionContextData => {
const [connections, setConnections] = useState<Connection[]>([])
const connect = async (
contactId: string,
source: string
) => {
try {
await ContactService.connectRep(contactId, source)
getConnections()
} catch (error) {
console.log(error)
}
}
const getConnections = async () => {
const getContactsResponse = await UserService.getConnections()
setConnections(getContactsResponse.data)
}
return {
getConnections,
connect,
}
}
export const ConnectionContext = createContext<ConnectionContextData>(
ConnectionContextDefaultValue
)
export const ConnectionProvider: React.FC = ({ children }) => {
return (
<ConnectionContext.Provider value={useConnectionContextValue()}>
{children}
</ConnectionContext.Provider>
)
}
MyComponent
import React, {useContext} from 'react'
import {ConnectionContext} from './context'
const MyComponent extends React.Component {
const { connect } = useContext(ConnectionContext)
render() {
return (
<>
<button onClick={() => connect('1234', 'Some source')}>
Click me
</button>
</>
)
}
}
export default MyComponent
Hopefully, this is enough context (pardon the sh!tty pun).
I'm trying to figure out how to test that ContactService.connectRep was called with contactId and source. Everything I've read says to avoid testing context directly, but I can only mock up connect as jest.fn().
I've mocked the context provider, and I can see that the connect function was called with contactId and source. That all passes just fine, but I'm not sure how to approach knowing how ContactService.connectRep was called. Any ideas?
I am new in react. Maybe someone can help me. I have 2 components. getData() in Weather Component should call the method getPoint() from the component PointsOfInterest. How can I do that?
Component 1:
import React from 'react';
import { getPoint, PointsOfInterest } from './PointsOfInterest'
class Weather extends React.Component {
getWeather = async (city) => {
...
}
}
getData = async (city) => {
await this.getWeather(city)
getPoint(this.state.latitude, this.state.longitude);
}
render()
{
return ... }
Component 2:
export class PointsOfInterest extends React.Component {
state = {nameOfPoints: ''}
fetchToken = async () => {
...
}
getPoint = async (latitude, longitude) => {
const auth = await this.fetchToken()
...
}
render(){
return(...)
}
}
export default PointsOfInterest;
While importing PointsOfInterest in weather component, you can have an additional prop ref in PointsOfInterst (as shown below) . By ref you can access the methods of PointsOfInterst in weather component. I have done the code changes below for Weather component
You can do like
import React from 'react';
import { getPoint, PointsOfInterest } from './PointsOfInterest'
class Weather extends React.Component {
constuctor(props){
// Changes made here
this.pointOfIntrst = React.createRef();
}
getWeather = async (city) => {
...
}
}
getData = async (city) => {
await this.getWeather(city)
if(this.pointOfIntrst.current) {
await this.pointOfIntrst.current.getPoint(this.state.latitude,
this.state.longitude);
}
}
render()
{
<PointsOfInterest ref = {this.pointOfIntrst} .../>
return ... }
I'd like to append a string to all url when I click on a button, how to do this ?
Here is the code
App.js
import React, { Component } from "react";
import Button from './Button';
let API = 'https://someurl.com/';
class App extends Component {
constructor(props) {
super(props);
this.state = {
results: []
};
this.updateUrl = this.updateUrl.bind(this);
}
componentWillMount = () => {
this.fetchData();
}
fetchData = async () => {
const response = await fetch(API);
const json = await response.json();
this.setState({
results: json.results
});
};
updateButton = (event) => {
this.setState({
API.concat('?format=fzjeozfij')
});
}
render() {
return (
<div>
<Button data={this.state} />
</div>
);
}
}
export default App;
Button.js
import React, { Component } from 'react';
class Button extends Component {
render() {
const updateButton = this.props.data;
return (
<button type="button" onClick={updateButton}>Button</button>
)
}
}
export default Button;
My goal is to get the url from const API to https://someurl.com/?format=zegizhgz
I think I have to modify the fetchData function to concat some string to the url but I'm not sure how to do it
updateButton = () => {
const nApi = `${this.state.api}?format=wookiee`;
this.setState({ api: nApi });
this.fetchData(nApi);
}
render() {
return (
<div>
<Button onClick={this.updateButton}/>
</div>
);
}
fetchData = async (api) => {
const response = await fetch(api);
const json = await response.json();
this.setState({
results: json.results
});
};
Button.jsx
import React, { Component } from 'react';
class Button extends Component {
render() {
const {onClick} = this.props;
return (
<button type="button" onClick={onClick}>Button</button>
)
}
}
I'm using react-lifecycle-component in my react app, and incurred in this situation where I need the componentDidMount callback to load some data from the backend. To know what to load I need the props, and I can't find a way to retrieve them.
here's my container component:
import { connectWithLifecycle } from "react-lifecycle-component";
import inspect from "../../../libs/inspect";
import fetchItem from "../actions/itemActions";
import ItemDetails from "../components/ItemDetails";
const componentDidMount = () => {
return fetchItem(props.match.params.number);
};
// Which part of the Redux global state does our component want to receive as props?
const mapStateToProps = (state, props) => {
return {
item: state.item,
user_location: state.user_location
};
};
// const actions = Object.assign(locationActions, lifecycleMethods);
export default connectWithLifecycle(mapStateToProps, { componentDidMount })(
ItemDetails
);
Any clues?
thanks.
import React, { Component } from 'react'
import { connect } from 'react-redux'
import fetchItem from '../actions/itemActions'
class Container extends Component {
state = {
items: []
}
componentDidMount() {
const { match } = this.props
fetchItem(match.params.number)
// if your fetchItem returns a promise
.then(response => this.setState({items: response.items}))
}
render() {
const { items } = this.state
return (
<div>
{ items.length === 0 ? <h2>Loading Items</h2> :
items.map((item, i) => (
<ul key={i}>item</ul>
))
}
</div>
)
}
const mapStateToProps = (state, props) => {
return {
item: state.item,
user_location: state.user_location
}
}
export default connect(mapStateToProps)(Container)
Though I don't see where you are using the props you take from your Redux store...
I am trying to test a little React component - Template block statement.
But do I can to do that? Because I can't even log that block statement from renderResult() method.
Is it possible? Only One way I see. It's just test the end result via Enzume Shallow. But I just wonder - is it possible?
Thanks for any info.
import React, { PropTypes } from "react";
export function zeta() {
return "zeta";
}
export default class AppComponent extends React.Component {
some() {
return "some";
}
renderResult() {
let res;
if (process.env.NODE_ENV === "production") {
res = ( <main><h1>App Component PROD</h1>{ this.props.children }</main> );
} else {
res = ( <main><h1>App Component DEV 11</h1>{ this.props.children }</main> );
}
return res;
}
render() {
return this.renderResult();
}
}
AppComponent.propTypes = {
children : PropTypes.object
};
My test
import jasmineEnzyme from "jasmine-enzyme";
import React from "react";
import {mount} from "enzyme";
import AppComponent, {zeta} from "../App.component";
describe("<AppComponent /> test", () => {
let wrapper;
beforeEach(() => {
jasmineEnzyme();
wrapper = mount(<AppComponent />);
});
it("App Component should contain h1", () => {
expect(wrapper.find("h1")).toBePresent();
});
it("h1 Should contain a dev text in case of dev mode", () => {
const compInst = wrapper.instance();
const res = compInst.some();
console.log(compInst.renderResult());
console.log(res);
expect(res).toMatch("some");
});
});
});