TypeScript - invoking React prop with Enzyme - reactjs

I'm trying to convert my Jest tests using Enzyme to TypeScript, but running into one particular case that I'm not sure how to handle. Basically, I'm trying to call a function that is passed as a prop to a sub-component. The error I'm seeing is:
spec/javascript/_common/components/sidebar_spec.tsx:85:5 - error TS2349:
Cannot invoke an expression whose type lacks a call signature. Type '{}' has no compatible call signatures.
85 component.find(Link).at(0).prop('onNavigate')();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How do I get past this error? Not sure if it's helpful, but more context for the test:
it('does not hide the sidebar after a link is clicked', () => {
const component = shallow(<Sidebar />);
component.find(Link).at(0).prop('onNavigate')();
component.update();
expect(component.find(Link)).toHaveLength(3);
});
And a chunk of code from the Sidebar component:
class Sidebar extends React.Component<any, any> {
...
hideIfMobile() {
const {mobile} = this.state;
if (mobile) { this.setState({visible: false}); }
}
render() {
const {visible} = this.state;
if (!visible) {
return (
<div className='sidebar sidebar--hidden'>
{this.sidebarToggle()}
</div>
);
}
const linkProps = {
baseClass: 'sidebar__link',
onNavigate: this.hideIfMobile,
};
return (
<div className='sidebar sidebar--visible'>
<h2 className='sidebar__header'>{'Menu'}{this.sidebarToggle()}</h2>
<hr className='sidebar__divider' />
<Link to='root' {...linkProps}><h2>{'FOCUS'}</h2></Link>
<Link to='tasks' {...linkProps}><h2>{'ALL TASKS'}</h2></Link>
<Link to='timeframes' {...linkProps}><h2>{'TIMEFRAMES'}</h2></Link>
</div>
);
}
}
the Link component is wrapped in react-redux:
import {connect} from 'react-redux';
import Link from 'src/route/components/link';
import {getRouteName} from 'src/route/selectors';
import {setRoute} from 'src/route/action_creators';
function mapStateToProps(state) {
return {routeName: getRouteName(state)};
}
export default connect(mapStateToProps, {setRoute})(Link);
and the actual component:
class Link extends React.Component<any, any> {
navigate(event) {
event.preventDefault();
const {onNavigate, params, setRoute, to} = this.props;
setRoute({name: to, ...params});
if (onNavigate) { onNavigate(); }
}
path() {
const {params, to} = this.props;
const pathParams = mapValues(params, value => value.toString());
return findRoute(to).toPath(pathParams);
}
className() {
const {baseClass, className, to, routeName} = this.props;
return classnames(
baseClass,
{[`${baseClass}--active`]: baseClass && routeName === to},
className,
);
}
render() {
const {children} = this.props;
return (
<a
href={this.path()}
className={this.className()}
onClick={this.navigate}
>
{children}
</a>
);
}
}

It turns out Link in this case was defined earlier in my test file as:
const Link = 'Connect(Link)';
I switched this to import the actual link container and it resolved the issue.
import Link from 'src/route/containers/link';

Related

How to fix problem with React-Redux(mapDispatchToProps() in Connect() must return a plain object. Instead received undefined.)

I ported my application to redux-thunk and the error started to appear in the console(
mapDispatchToProps() in Connect(UsersContainer) must return a plain object. Instead received undefined.).
But with the appearance of this error, nothing has changed. How to fix it?
Reducer:
import {getTeamApi} from "./api";
let date = {
teamDate: []
};
const realtorsDate = (state = date, action) => {
switch (action.type) {
case "GetTeam":
return {...state, teamDate: [...state.teamDate, ...action.team]};
default:
return state
}
}
export let GetTeam = (team) => ({
type: "GetTeam",
team
})
export default realtorsDate;
export const getTeamThunks = () => {
return (dispatch) => {
getTeamApi.then(response => {
dispatch(GetTeam(response.items));
});
}
}
Container component:
import {connect} from "react-redux";
import {getTeamThunks} from "../../store/realtorsDate";
import ScrollableAnchor from "react-scrollable-anchor";
import MainFourth from "./main-fourth";
import Photo from "../../Images/pivo-3.jpg";
import React from "react";
class UsersContainer extends React.Component {
render() {
return (
<section>
<ScrollableAnchor id={"team"}>
<h2>Наша команда</h2>
</ScrollableAnchor>
<div className="MainFourth">
{this.props.realtorsDate.map((el, i) => (
<MainFourth key={i} el={el} Photo={Photo}></MainFourth>))}
</div>
</section>
);
}
}
let MapStateToProps = (state) => {
return {
realtorsDate: state.realtorsDate.teamDate
}
}
let FourthContainerBlock = connect(MapStateToProps, getTeamThunks)(UsersContainer)
export default FourthContainerBlock
Component:
import React from "react";
import "./../../css/App.css";
import {FontAwesomeIcon} from "#fortawesome/react-fontawesome";
import {faAt, faMobileAlt} from "#fortawesome/free-solid-svg-icons";
class MainFourth extends React.Component {
render() {
return (
<div className="team" key={this.props.i}>
<div className="about-team">
<h2 className="team-name">
{this.props.el.SecondName}
{this.props.el.Name}
</h2>
<h2 className="team-position">{this.props.el.Position}</h2>
<p><FontAwesomeIcon icon={faMobileAlt}></FontAwesomeIcon> : {this.props.el.Phone}</p>
<p><FontAwesomeIcon icon={faAt}></FontAwesomeIcon> : {this.props.el.Mail}</p>
</div>
<img className="TeamsPhoto" src={this.props.Photo} alt="" />
</div>
);
}
}
export default MainFourth;
Ty all
The error is actually pretty straight forward, getTeamThunks should return a js object and that should be synchronous. You can do asynchronous things in the action creators.
The second argument to connect is simply used to map the dispatch to props(the reason why most tend to name it as such).
For example, mapDispatchToProps can look like this:
const mapDispatchToProps = (dispatch) => {
return {
getTeamThunks: () => dispatch(actions.getTeamThunksData())
}
}
let FourthContainerBlock = connect(MapStateToProps, mapDispatchToProps)(UsersContainer)
Now the getTeamthunksData can be written like this:
export const getTeamThunksData = () => {
return (dispatch) => {
getTeamApi.then(response => {
dispatch(GetTeam(response.items));
});
}
}
In your component, you can dispatch it by using this.props.getTeamThunks(). Where you execute it depends on your requirements.

How to use React Ref with Styled Component

I am running React 16.8.6 and Styled Components 4.3.2 currently and am hitting an issue trying to use React.forwardRef.
In Comments.js
import CommentItem from './CommentItem';
class Comments extends Component {
constructor(props) {
super(props);
this.items = [];
}
componentDidMount() {
console.log(this.items);
}
render() {
const { comments } = this.props;
return (
<div>
{comments.length > 0 &&
comments.map((comment, i) => {
this.items[i] = React.createRef();
return (
<CommentItem
ref={this.items[i]}
key={comment.id}
comment={comment}
/>
);
})}
</div>
);
}
}
In CommentItem.js
import styled from "styled-components";
import { Media } from "react-bulma-components";
const CommentMediaWrapper = styled(Media)`
position: relative;
`;
const CommentItem = React.forwardRef(
({ comment }, ref) => {
return (
<CommentMediaWrapper ref={ref}>
<div>...</div>
</CommentMediaWrapper>
);
}
);
export default CommentItem;
In Comments.js will console an array [{ current: null },...]
I don't know how to pass ref in to CommentMediaWrapper. I don't want add new element outer or inner CommentMediaWrapper. Thank for your help.
I think the issue here is more to do with the library element Media from react-bulma-components that you are wrapping. This component exposes a prop named domRef that can be used to pass the DOM reference to the HTML element underneath the wrappers.
const CommentItem = React.forwardRef(
({ comment }, ref) => {
return (
<CommentMediaWrapper domRef={ref}>
<div>...</div>
</CommentMediaWrapper>
);
}
);
Github Reference

createPortal does not overwrite div contents (like ReactDOM.render)

I am trying to get ReactDOM.createPortal to override the contents of the container I am mounting it too. However it seems to appendChild.
Is it possible to override contents? Similar to ReactDOM.render?
Here is my code:
import React from 'react';
import { createPortal } from 'react-dom';
class PrivacyContent extends React.Component {
render() {
return createPortal(
<div>
<button onClick={this.handleClick}>
Click me
</button>
</div>,
document.getElementById('privacy')
)
}
handleClick() {
alert('clicked');
}
}
export default PrivacyContent;
If you know what you're doing, here is a <Portal /> component that under the hoods creates a portal, empties the target DOM node and mounts any component with any props:
const Portal = ({ Component, container, ...props }) => {
const [innerHtmlEmptied, setInnerHtmlEmptied] = React.useState(false)
React.useEffect(() => {
if (!innerHtmlEmptied) {
container.innerHTML = ''
setInnerHtmlEmptied(true)
}
}, [innerHtmlEmptied])
if (!innerHtmlEmptied) return null
return ReactDOM.createPortal(<Component {...props} />, container)
}
Usage:
<Portal Component={MyComponent} container={document.body} {...otherProps} />
This empties the content of document.body, then mounts MyComponent while passing down otherProps.
Hope that helps.
In the constructor of the component, you could actually clear the contents of the div before rendering your Portal content:
class PrivacyContent extends React.Component {
constructor(props) {
super(props);
const myNode = document.getElementById("privacy");
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
}
render() {
return createPortal(
<div>
<button onClick={this.handleClick}>
Click me
</button>
</div>,
document.getElementById('privacy')
)
}
handleClick() {
alert('clicked');
}
}
export default PrivacyContent;
I find this is better and doesn't need useState:
export const Portal = () => {
const el = useRef(document.createElement('div'));
useEffect(() => {
const current = el.current;
// We assume `root` exists with '?'
if (!root?.hasChildNodes()) {
root?.appendChild(current);
}
return () => void root?.removeChild(current);
}, []);
return createPortal(<Cmp />, el.current);
};
Bit of an old question, but here's another sync solution (without useState). Also in a reusable component format.
const Portal = ({ selector, children, replaceContent = true }) => {
const target = useRef(document.querySelector(selector)).current;
const hasMounted = useRef(false);
if (!target) return null;
if (replaceContent && !hasMounted.current) {
target.innerHTML = '';
hasMounted.current = true;
}
return createPortal(children, target);
};
A solution with zero hook dependencies
import { createPortal } from 'react-dom';
const getNode = (id) => {
const domNode = document.getElementById(id);
const div = document.createElement("div");
domNode?.replaceChildren(div);
return div;
};
const Portal = ({ children }) => {
const domNode = getNode("privacy");
if (domNode) {
return createPortal(children, domNode);
}
return null;
};

React lazy does not cause splitting bundle in chunks

As in the title, I'm trying to use React.lazy feature which works in my my other project. But not in this one, I don't know what I'm missing here. All works just fine, no errors, no warnings. But for some reason I don't see my bundle split in chunks.
Here's my implementation:
import React, { Component, Suspense } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { getApps } from '../../actions/apps';
import './_apps.scss';
const AppItemComponent = React.lazy(() => import('../AppItem'));
class Apps extends Component {
componentDidMount() {
const { getApps } = this.props;
getApps(3);
}
renderAppItem = () => {
const { apps } = this.props;
return apps && apps.map((item, i) => {
return (
<Suspense fallback={<div>loading...</div>} key={i}>
<AppItemComponent
index={i + 1}
item={item}
/>
</Suspense>
);
});
};
render() {
const { apps } = this.props;
return (
<div className="apps__section">
<div className="apps__container">
<div className="apps__header-bar">
<h3 className="apps__header-bar--title">Apps</h3>
<Link className="apps__header-bar--see-all link" to="/apps">{`see all (${apps.length})`}</Link>
</div>
{this.renderAppItem()}
</div>
</div>
);
}
}
const mapStateToProps = ({ apps }) => {
return { apps };
};
const mapDispatchToProps = dispatch => {
return {
getApps: quantity => dispatch(getApps(quantity)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Apps);
I'm doing this in react-create-app app and in react v16.6, react-dom v16.6.
What am I missing here?
I also have the same problem, then I have resolved this case without using Suspense and lazy(try code below), and I can see chunks file. However, after using this way, I try changing my code again with Suspense and lazy. It works!!! and I don't know why it does. Hope that it works for someone find solution for this case.
1 - create file asyncComponent
import React, { Component } from "react";
const asyncComponent = (importComponent) => {
return class extends Component {
state = {
component: null,
};
componentDidMount() {
importComponent().then((cmp) => {
this.setState({ component: cmp.default });
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
};
};
export default asyncComponent;
2 - and in App.js, example:
const AuthLazy = asyncComponent(() => import("./containers/Auth/Auth"));
//Route
<Route path="/auth" component={AuthLazy} />
Check that your component is not imported somewhere with regular import: import SomeComponent from './path_to_component/SomeComponent';
Check that component is not re-exported somewhere. (For example in index.js (index.ts) file: export * from './SomeComponent') If so, just remove re-export of this component.
Check that your export your component as default or use code like this:
const SomeComponent = React.lazy(() => import('./path_to_component/SomeComponent').then((module) => ({ default: module.SomeComponent })));

function argument in component's constructor in react.js

When I look at the following line in this example:
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
then I don't understand where is the lambda function ({value}) => <li>{value}</li> used in SortableElement ?
Can someone please enlighten me ?
SortableElement's code:
import React, {Component, PropTypes} from 'react';
import {findDOMNode} from 'react-dom';
import invariant from 'invariant';
// Export Higher Order Sortable Element Component
export default function SortableElement (WrappedComponent, config = {withRef: false}) {
return class extends Component {
static displayName = (WrappedComponent.displayName) ? `SortableElement(${WrappedComponent.displayName})` : 'SortableElement';
static WrappedComponent = WrappedComponent;
static contextTypes = {
manager: PropTypes.object.isRequired
};
static propTypes = {
index: PropTypes.number.isRequired,
collection: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
disabled: PropTypes.bool
};
static defaultProps = {
collection: 0
};
componentDidMount() {
let {collection, disabled, index} = this.props;
if (!disabled) {
this.setDraggable(collection, index);
}
}
componentWillReceiveProps(nextProps) {
const {index} = this.props;
if (index !== nextProps.index && this.node) {
this.node.sortableInfo.index = nextProps.index;
}
if (this.props.disabled !== nextProps.disabled)
{
let {collection, disabled, index} = nextProps;
if (disabled) {
this.removeDraggable(collection);
}
else {
this.setDraggable(collection, index);
}
}
}
componentWillUnmount() {
let {collection, disabled} = this.props;
if (!disabled) this.removeDraggable(collection);
}
setDraggable(collection, index){
let node = this.node = findDOMNode(this);
node.sortableInfo = {index, collection};
this.ref = {node};
this.context.manager.add(collection, this.ref);
}
removeDraggable(collection) {
this.context.manager.remove(collection, this.ref);
}
getWrappedInstance() {
invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call');
return this.refs.wrappedInstance;
}
render() {
const ref = (config.withRef) ? 'wrappedInstance' : null;
return (
<WrappedComponent ref={ref} {...this.props} />
);
}
}
}
export default function SortableElement (WrappedComponent, config = {withRef: false}) {
return class extends Component {
...
render() {
const ref = (config.withRef) ? 'wrappedInstance' : null;
return (
<WrappedComponent ref={ref} {...this.props} />
);
}
}
}
Look at the render() method in the returned React Component by the higher order SortableElement function, the lambda function (which is a stateless component) is passed as the first argument to the higher order function, and this first argument is going to end up as being the parameter WrappedComponent you see in the signature of this higher order function.
So this higher order function is going to spit a React component with a render() method that uses/calls your actual React component that you just passed in (the lambda function).
<WrappedComponent ref={ref} {...this.props} />
Thanks to ({value}) => <li>{value}</li> in
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
we will be actually rendering an li element with a value passed as a prop from the map method below.
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) =>
<SortableItem key={`item-${index}`} index={index} value={value} />
)}
</ul>
);
});
In the context of the SortableElement's API code the important thing is that it renders the WrappedComponent (lines 67-69). We can treat SortableElement as any other Higher Order Component - a component that wraps another component to deliver some extra functionality. In this case - a fancy sorting animation of the lambda function.
Put simply
({value}) => <li>{value}</li> is a short hand for
React.crateClass({
render:function(){
return <li>{this.props.value}</li>
}
})
refer to pure functional component in React
and SortableElement is a higher order component wrapping another React component ,such the functional component above

Resources