I'm trying to use flatpickr("^4.6.3)" in a react project that uses webpack as the module bundler. I get this error in this code:
import React, { useRef, useCallback } from 'react';
import flatpickr from 'flatpickr';
import 'flatpickr/dist/themes/light.css';
function MyComponent() {
const flatpickerIn = useRef(null);
const flatpickrOptions = {
enableTime: true,
allowInput: true,
dateFormat: "Y-m-d h:i K"
// noCalendar: true,
};
const inputRefcallback = useCallback(node => {
if (node !== null && !flatpickerIn.current) {
flatpickerIn.current = flatpickr(node, flatpickrOptions);
}
}, [flatpickrOptions]);
return (
<input
name="startDate"
placeholder="YYYY/MM/DD"
style={{ width: 'auto' }}
ref={startDateRef}
/>
)
}
TypeError: flatpickr__WEBPACK_IMPORTED_MODULE_5___default(...) is not a function
One strange fact is that this code works when rendering the component in storybook. Any ideas to fix this?
It seems like the problem was with the uglify plugin I am using. The error disappeared after I imported flatpickr like so:
import flatpickr from 'flatpickr/dist/flatpickr.min';
Related
I'm trying to use an npm package called hover-effect inside a functional component, but I'm constantly bumping into some issues. I have used similar packages in create-react-app before but I'm new to next.js. See below how the package should be used:
import React, { useEffect, useRef } from "react";
import HoverEffect from "hover-effect";
export default Card(){
const container = useRef();
useEffect(() => {
console.log(container.current);
new HoverEffect({
parent: container.current,
intensity: 0.3,
image1: "https://picsum.photos/420/620",
image2: "https://picsum.photos/420/620",
displacementImage:
"https://raw.githubusercontent.com/robin-dela/hover-effect/master/images/fluid.jpg",
});
}, [container]);
return(
<>
<div
className="outer-image"
ref={container}
id="imgContainer"
style={{ height: 500, width: 400 }}
>
</div>
</>
)
First of all, I tried to import it like any other npm module, but I get the issue
SyntaxError: Cannot use import statement outside a module
I have tried to import the package dynamically using next/dynamic in this way:
const HoverEffect = dynamic(() => import('hover-effect')), {ssr: false});
But when I try to use 'new' syntax I get the error 'HoverEffect' is not a constructor.
I even tried adding next js transpile module as
next.config.js:
const withTM = require("next-transpile-modules")([
"gsap",
"hover-effect",
]);
module.exports = withTM();
Anyone aware of any solution would be a lifesaver
I just tried to import it in my localhost. This solution is working fine
const withTM = require("next-transpile-modules")([
"gsap",
"hover-effect",
]);
module.exports = withTM();
You also need to make sure that your import is like this
import HoverEffect from "hover-effect";
I need such an editor on react https://cloverhearts.github.io/quilljs-markdown/ , as you can see in it you can put markdown characters directly into the text.
when I do this
import React, { Component } from 'react'
import './App.css'
import ReactQuill from 'react-quill'
import Quill from 'quill'
import QuillMarkdown from 'quilljs-markdown'
const App = () => {
const editor = new Quill('#editor', {
theme: 'snow'
})
new QuillMarkdown(editor)
return (
<div className='app'>
{/*<MyComponent/>*/}
<div id="editor"></div>
</div>
)
}
export default App
I get error TypeError: Cannot read property 'on' of undefined
as I understand I need jQuery for work, but I use react, I found https://www.npmjs.com/package/react-quill this quilljs for react, but I don't know how to combine it with markdown https://www.npmjs.com/package/quilljs-markdown
can anyone help?
I found the solution for this after hours of trying this out.
What you have to do is this:
Create a module for ReactQuill
Register the module.
Pass modules to react quill
Shown Below.
Step 01
const modules = {
markdownOptions: {}
};
Step 02
Quill.register('modules/markdownOptions', QuillMarkdown);
Step 03
<ReactQuill
modules={modules}
/>
It seems like you are trying to initialize the Quill instance and the markdown module before the editor is ready.
Use useEffect hook to initialize it after the div has been rendered:
import {useEffect} from 'react';
...
useEffect(() => {
const editor = new Quill('#editor', {
theme: 'snow'
});
new QuillMarkdown(editor);
});
I'm trying to use jest-dom to test a component's styles, and I'm having the error:
"TypeError: expect(...).toHaveStyle is not a function"
My component is a simple link with styled-components:
import styled from 'styled-components'
export const Link = styled.a`
color: #fff;
`
In my test I'm doing:
describe('Link', () => {
it('should display color on the link', () => {
render(<Link href="/x">Test</Link>)
}
expect(screen.getByRole('link', { name: /test/i })).toHaveStyle({ color: '#fff' })
}
I created a settings file (jest.config.js) with:
module.exports = {
setupFilesAfterEnv: ['<rootDir>/.jest/setup.js'],
}
At the root of the project I created the .jest / setup.js file and imported the js-dom:
import '#testing-library/jest-dom'
From https://testing-library.com/docs/svelte-testing-library/setup/
6.2 Add the following to your Jest configuration in package.json
{
"setupFilesAfterEnv": ["#testing-library/jest-dom/extend-expect"]
}
You could add it to your jest.config.js since you already have that, rather than package.json.
Since #testing-library/dom v5.0.0, there are some breaking changes compare/v4.2.4...v5.0.0
Before v5.0.0, you should use import '#testing-library/jest-dom/extend-expect';
Since v5.0.0, you should use import '#testing-library/jest-dom';
You didn't add the matchers for expect correctly. That's the reason you get the error.
you can try this :
import { toHaveStyle } from '#testing-library/jest-dom'
expect.extend({ toHaveStyle })
it works for me.
Use the following versions in your package:
"dependencies": {
"#types/styled-components": "5.9.1",
"styled-components": "^5.2.0"
},
and import this package into your test file:
import '#testing-library/jest-dom/extend-expect'
I found the answer from this link
To be short:
Run: npm install --save-dev #testing-library/jest-native
Add: import '#testing-library/jest-native/extend-expect' to your test file
Add: import { toHaveStyle } from '#testing-library/jest-native/dist/to-have-style'
Add: expect.extend({toHaveStyle})
Finally, you have the toHaveStyle for your expect
Sample code:
/**
* #format
*/
import 'react-native';
import '#testing-library/jest-native/extend-expect';
import React from 'react';
import App from '../App';
import {render, screen} from '#testing-library/react-native';
import { toHaveStyle } from '#testing-library/jest-native/dist/to-have-style';
expect.extend({toHaveStyle})
it('renders correctly', () => {
render(<App/>);
const text = screen.getByTestId('Sample Text')
expect(text).not.toBeNull();
const button = screen.getByTestId('Sample Button')
expect(button).not.toBeNull();
expect(button).toHaveStyle({
backgroundColor: 'transparent'
})
});
install jest-styled-components
npm i -D install jest-styled-components
then use .toHaveStyleRule
Example:
import React from 'react';
import { render } from 'react-testing-library';
import Button from '../Button';
import 'jest-styled-components';
describe('<Button />', () => {
it('should render text', () => {
const { getByText } = render(<Button text="Button" />);
expect(getByText('Button')).not.toBeNull();
});
it('should have correct style with background color', () => {
const { getByText } = render(<Button text="Button" color="#fff" />);
expect(getByText('Button')).toHaveStyleRule('background', '#fff');
});
});
I keep getting this error when trying to test a button component. I have changed Jest's config settings here and there but nothing has worked, can anyone tell me the answer so I can stop pulling my hair out?
I am using expo to demo the app, the problem seems to lie within the font that it's trying to render on the nav button, Jest/React doesn't understand it.
The failure:
FAIL tests/Components/NavigationButton.test.js
● Test suite failed to run
C:\..\node_modules\#expo\vector-icons\Zocial.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Zocial from './build/Zocial';
^^^^^^
SyntaxError: Unexpected identifier
at ScriptTransformer._transformAndBuildScript (node_modules/#jest/transform/build/ScriptTransformer.js:537:17)
at ScriptTransformer.transform (node_modules/#jest/transform/build/ScriptTransformer.js:579:25)
at Object.<anonymous> (node_modules/react-native-elements/src/helpers/getIconType.js:1:1)
NavigationButton.js:
import React from "react";
import { StyleSheet } from "react-native";
import { Button } from "react-native-elements";
import Icon from "react-native-vector-icons/FontAwesome";
import { withNavigation } from 'react-navigation';
const NavigationButton =(props) => {
return (
<Button data-test="nav_button"
icon={<Icon name={props.icon} size={30} color="white" style={styles.iconStyle} />}
raised
color="white"
buttonStyle={styles.button}
title={props.title}onPress={() => props.navigation.navigate(props.navName)}
/>
);
};
const styles = StyleSheet.create({
button: {
minWidth:150,
alignSelf:'center',
},
iconStyle:{
marginHorizontal:10
}
});
export default withNavigation(NavigationButton);
NavigationButton.test.js:
/**
* #format
*/
import 'react-native';
import React from 'react';
import { shallow } from 'enzyme';
import { findByTestAtt } from '../../Utils/test_utils';
import NavigationButton from '../../src/Components/NavigationButton'
// Note: this is just for use with Jest snapshot testing
// and comes packaged with react-native init project.
// You do not need this if using Enzyme 'toMatchSnapshot' etc.
import renderer from 'react-test-renderer';
// setup for shallow rendering component, saves having to do it in every test in this file
const setup = (props = {}) => {
const component = shallow(<NavigationButton {...props} />);
return component;
};
describe('NavigationButton tests: ', () => {
let component;
beforeEach(() => {
component = setup();
});
it('Button renders correctly: ', () => {
console.log(component.debug());
const wrapper = findByTestAtt(component, 'nav_button');
expect(wrapper.length).toBe(1);
});
});
Using the jest-expo preset solved the problem for me. The documentation explains it well: https://www.npmjs.com/package/jest-expo. The issue seemed to be that the import keyword wasn't being transformed, I'm not clear on why but it came up in an issue here: https://github.com/expo/expo/issues/5296
I want to use marked in reactjs as described in the reactjs docs.
<div>{marked(mystring)}</div>
I use babel so I import marked like this:
import { marked } from 'marked';
Unfortunately the import statement does not work. marked is not defined.
How do I have to import marked here, so that I can use it?
Here's one way to use marked with React:
Ensure that you've installed marked
Include marked in your project's package.json file:
// package.json
{
dependencies: {
react: "^17.0.0",
marked: "^4.0.0",
},
}
Import marked in your .jsx (or related) file:
import { marked } from "marked";
Use the dangerouslySetInnerHTML approach as shown in the example below:
import React from "react";
import { marked } from "marked";
class MarkdownExample extends React.Component {
getMarkdownText() {
var rawMarkup = marked.parse("This is _Markdown_.");
return { __html: rawMarkup };
}
render() {
return <div dangerouslySetInnerHTML={this.getMarkdownText()} />;
}
}
The dangerouslySetInnerHTML attribute gives you the ability to work with raw (HTML) markup. Make sure to take care when using this attribute, though!
Alternative (Safe)
If you don't want to use dangerouslySetInnerHTML and safely render HTML. Try marked-react, which internally uses marked to render the html elements as react components
npm i marked-react
import Markdown from "marked-react";
const MarkdownComponent = () => {
return <Markdown>{rawmarkdown}</Markdown>;
};
Another alternative is react-markdown
Here is another way of using marked with React Hooks:
Create your MarkedConverter component
import { useState } from 'react'
import marked from 'marked'
export const MarkedConverter = () => {
const [markedVal, setMarkedVal] = useState(
'# Welcome to my React Markdown Previewer!'
)
return <div dangerouslySetInnerHTML={createMarkUp(markedVal)}></div>
}
Create Markup function and pass the value from MarkedConverter Component
export const createMarkUp = (val) => {
return { __html: marked(val) }
}
Finally you can import MarkedConverter Component to any of your Component
With the marked-wrapper react-marked-markdown:
import { MarkdownPreview } from 'react-marked-markdown'
export default ({ post }) => (
<div>
<h1>{ post.title }</h1>
<MarkdownPreview value={ post.content }/>
</div>
)
If you just want to import marked:
import marked from 'marked';
Then call the function in your component:
marked('# Markdown');
Here's an example on how to use marked with react:
Install marked with NPM : npm i marked
import it in your react app (this example is created with create-react-app), and using it
example of a react component using "marked"
result in the browser :
preview