FindDOMNode flux/alt store - javascript

I'm trying to access a dom node from a store (using alt) in order to animate using velocity.js, however am only getting 'cannot read property of undefined'. Is it possible to use findDOMNode from an alt/flux store?
import React from 'react'
import alt from '../_alt';
import Actions from '../actions/actions';
import Velocity from 'velocity-animate/velocity';
import Body from '../modules/level_1/body/body1'
class Store {
constructor(){
this.bindListeners({
menuToggle: Actions.MENU_TOGGLE
});
this.menuStatus = false
}
menuToggle(){
if (!this.menuStatus){
this.menuStatus = true;
Velocity(React.findDOMNode(Body.refs.wrap),({ width: '50px' }), 50)
} else {
this.menuStatus = false;
}
}
}
export default alt.createStore(Store, 'Store');
Component:
import React from 'react';
import connectToStores from 'alt/utils/connectToStores';
import Store from '../../../stores/store'
import Actions from '../../../actions/actions';
import Styles from './body1.css';
import Hero from '../../objects/hero/full_width'
let image = ['../../../../assets/full_width1.jpg', 'image']
#connectToStores
export default class Body extends React.Component {
static getStores(){
return [Store];
}
static getPropsFromStores(){
return Store.getState();
}
render(){
return (
<div ref='wrap'>
<Hero content={image} />
</div>
);
}
}

Body is a react class, which does not have refs.
What you need is a react element (an instance of a react class) which is the "this" inside of render, componentDidMount, etc.
You will have to provide the react element to the store in some way (probably by calling menuToggle with the actual react element).
Alternatively you could use componentDidMount to set the ref on the Body class so that toggle could consume it.

A pattern that I have used with some success is to create an initialize action that takes as one of its arguments a React component. Then in componentDidMount() you can call that action, passing this as an argument. This allows your store to have a handle on that React element, as well as all of its associated properties so you can do things like React.findDOMNode(component.refs['someref']).

Related

Can i update Context API state in javascript class?

I have a Bluetooth class and listener method. I want to update my state in Bluetooth class and i will show in functional component.
JavaScript Class
import React, { Component } from "react";
import { MySampleContext } from "../../contexts/MySampleContext";
export class BluetoothClass extends Component {
static contextType = MySampleContext;
sampleBluetoothListener(value){
this.context.updateMyState(value);
}
}
This is my error.
TypeError: undefined is not an object (evaluating 'this.context.updateMyState')
Yes you can, you can pass data down to your component tree using Context API.
// Context file
import React from 'react';
const FormContext = React.createContext();
export default FormContext;
// Parent Class Component
import FormContext from "../context";
class ParentClass extends Component {
state = { name: "John Doe" };
render() {
return (
<FormContext.Provider value={this.state.name}>
<ChildClass />
</FormContext.Provider>
);
}
}
// Child Class Component
import FormContext from "../context";
class ChildClass extends Component {
render() {
return (
<FormContext.Consumer>
{(context) => {
console.log(context);
}}
</FormContext.Consumer>
);
}
}
The value prop in the context API takes an object, in which you could add a method that changes your state and pass it down to your component tree.
I advice you to take a quick look at the official Context API docs by React for a better understanding.
Thanks for all answers. But i mean pure "javascript class" not component, without rendering and react hooks is component based. Finally i solve problem with call back functions.

call react component-element as variable

Is it possible to call a React component element with a variable inside?
import React from "react"
/*React functional component*/
function someName() {
const someVar = "componentName"; //the name of the called component
return(
<{someVar}/>
)
}
export default someName;
I try to implement this in a router and to change the filenames(Sites) (in the element) dynamically with useState from fetched data.
I am open to all kind of help :)
There is no direct way to do that but you can use this approach.
import ComponentA from '...path';
import ComponentB from '...path';
...
const components = {
componentA: ComponentA,
componentB: ComponentB,
...
}
...
function App(props) {
const TargetComponent = components[props.componentName];
return <TargetComponent />;
}

Jest expected mock not called (redux component)

In React, I am testing that a button click inside a child component causes a function to be called in the parent component (onDeleteClick), via event bubbling.
For this test, I am using mount, as shallow will not allow us to trigger a function in a child component.
onDeleteClick, the function I am trying to check whether it was called or not, is a class property which in this case, is an arrow function.
I am mocking the onDeleteClick function, and passing it into my component via a Redux Provider when starting the test.
The problem I am having is that at the end of the test, when I perform a check to see if the mocked function was called, it returns 0.
expect(onDeleteClick.mock.calls.length).toBe(1);
If I put a console.log within onDeleteClick(), it's outputted during the test, so I know that the function is in fact being called.
I have researched this quite a bit and so far haven't gotten anything to work.
Some suggestions were to spy on my mocked function, and then call forceUpdate on the wrapper, but this didn't yield any positive results.
For this, I am using Jest with Enzyme.
Reference Code:
Parent.js
import { deleteAccount } from '../../actions/profileActions';
import ChildComponent from '../common/ChildComponent';
class ParentComponent extends Component {
onDeleteClick = () => {
console.log('onDeleteClick was executed during this test!')
this.props.deleteAccount();
}
render() {
let dashboardContent;
dashboardContent = (
<div>
<ChildComponent onDelete={this.onDeleteClick} />
</div>
);
return (
<div>
{dashboardContent}
</div>
);
}
}
// propTypes and mapStateToProps removed from this post
export default connect(
mapStateToProps,
{ deleteAccount }
)(ParentComponent);
__tests__/ParentComponent.js
import React from 'react';
import { mount } from 'enzyme';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import ParentComponent from '../ParentComponent';
import thunk from "redux-thunk";
const mockStore = configureStore([thunk]);
const deleteAccount = jest.fn();
const props = {
deleteAccount
}
const randomTestState = {
// some initial state, not important
};
const randomTestStore = mockStore(randomTestState);
describe('<ParentComponent />', () => {
it(`mounts the ParentComponent component and, when ChildComponent sends onDelete, then deleteAccount function is called once`, () => {
const wrapper = mount(
<Provider store={randomTestStore} props={props}>
<Router >
<ParentComponent />
</Router>
</Provider>
);
// Here, I grab an element in ChildComponent and simulate a click using Enzyme, then the event bubbles up, and deleteAccount() is called in the parent component.
// the console.log we expect to see from onDeleteClick is logged to console.
// the call does not seem to have registered though and the expect returns falsy
expect(deleteAccount.mock.calls.length).toBe(1);
})
});
Could the problem be that I am wrapping the component in a Provider?
I have a hunch, but I couldn't find any concrete examples of tests which use a Provider to wrap their component when running integration testing
The solution was that I needed to change my main ParentComponent file from
class ParentComponent extends Component {
to this:
extend class ParentComponent extends Component {
and then in my test file, import the component like so:
import { ParentComponent } from '../ParentComponent'; // non-default export should be wrapped in braces
and then update my test so that I assign the wrapper variable like so:
const wrapper = mount(<ParentComponent {...props} />);
This then allowed the test to pass
expect(deleteAccount.mock.calls.length).toBe(1);
It was recommended here in the Redux docs

Creating a class in react and exporting with higher order components

I am writing a class in React and exporting it with a higher order component, presently I have ...
import React, { Component } from 'react';
import { withRouter } from 'react-router';
/**
Project Editor
*/
class SpiceEditorRaw extends Component { ... }
const SpiceEditor = withRouter(SpiceEditorRaw);
export default SpiceEditor;
Then In a different file I import SpiceEditor and subclass it with
import SpiceEditor from './SpiceEditor'
class NameEditor extends SpiceEditor {
constructor(props){ ... }
...
render () { return (<h1> hello world <h1/>) }
}
However I am getting error:
index.js:2178 Warning: The <withRouter(SpiceEditorRaw) /> component appears to have a render method, but doesn't extend React.Component. This is likely to cause errors. Change withRouter(SpiceEditorRaw) to extend React.Component instead.
I believe it is possible to create a compoenent using withRouter, so I must be syntaxing incorrectly?
You should generally not use extends on any other component than React.Component. I think the Composition vs Inheritance part of the documentation is a great read on this subject.
You can accomplish almost everything with composition instead.
Example
import SpiceEditor from './SpiceEditor'
class NameEditor extends React.Component {
render () {
return (
<SpiceEditor>
{ /* ... */ }
</SpiceEditor>
)
}
}

how to create a class and another classes extends that class in react js

I am a beginner in react js, before react I was working with angular2 and backbone,and now my problem is I want to create a class such that all of my requests send from this class,like this:
class Ext {
get(url){
$.ajax({
url : url,
success : function(res){},
and ......
});
}
}
in my another component that use from my Ext function :
export default Ext;
import React from 'react';
import {render} from 'react-dom';
import {Ext} from "./module/Ext"
class App extends React.Component {
constructor(props) {
super(props);
/// Ext.get();
}
render () {
return(
<p> Hello React!</p>
);
}
}
render(<App/>, document.getElementById('app'));
how to extends from Ext ??? what is the best way ?
If your get(url) method is something general, it would be wise to have it as part of a separate module, then import and use it in any component you would like.
If, on the other hand, you want to implement a functionality right into a react component, the new ES2015 way of doing it would be by using Composition.
You first create what's called a HOC (Higher order component), which basically is just a function that takes an existing component and returns another component that wraps it. It encapsulates your component and gives it functionality you want, like with mixins but by using composition instead.
So your example would look like something like this:
import React from 'react';
export default const Ext = (Component) => class extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
let result = this.get('some_url').bind(this)
this.setState({ result })
}
get(url) {
$.ajax({
url : url,
success : function(res){
return res;
}
});
}
render() {
// pass new properties to wrapped component
return <Component {...this.props} {...this.state} />
}
};
Then you can just create a stateless functional component and wrap it with the HOC:
import React from 'react';
import Ext from './module/Ext';
class App {
render () {
return <p>{this.result}</p>;
}
}
export default Ext(App); // Enhanced Component
Or using ES7 decorator syntax:
import { Component } from 'react';
import Ext from './module/Ext';
#Ext
export default class App extends Component {
render () {
return <p>{this.result}</p>;
}
}
You can read this post for more details: http://egorsmirnov.me/2015/09/30/react-and-es6-part4.html

Categories

Resources