I'm learning react and it's my first time using a library in react. I'm trying to use watermark-js. I've read articles about how I to add npm packages in my react package.json using npm install <library name> save. Here is the part of package.json which show the watermarkjs
"dependencies": {
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "2.1.8",
"save": "^2.4.0",
"watermarkjs": "^2.0.0"
Now in my App.js component I've imported it as a module and use the snippet provided by watermarkjs in componentDidMount method as in react documentation. below is my complete App.js component.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Form from './Components/Form';
import ImageWaterMark from './Components/ImageWaterMark';
import image1 from './test-image.jpg'
import image2 from './download.jpg'
import { watermark } from 'watermarkjs'
class App extends Component {
componentDidMount() {
//Snippit
watermark([{ image1 }, { image2 }])
.image(watermark.image.lowerRight(0.5))
.then(function (img) {
document.getElementById('lower-right').appendChild(img);
});
}
render() {
return (
<div className="App">
<div ref="water"></div>
</div>
);
}
}
export default App;
There are 2 problem that I can't seem to understand. first
How can I pass this snippet as a ref to the render method as in
documentation?
Second the App through the following error
TypeError: Cannot read property 'watermark' of undefined
I've read many articles and watched videos but I haven't understand the concept of using libraries. Any help would be much appreciated.
watermarkjs uses a default export, not a named export. Change this:
import { watermark } from 'watermarkjs'`
To this:
import watermark from 'watermarkjs'
As for how to use it, once it loads you should call setState with the result. This will render your component again, and you can use that value however you see fit. For example:
componentDidMount() {
watermark([{ image1 }, { image2 }])
.image(watermark.image.lowerRight(0.5))
.then((img) => {
this.setState({ img });
});
}
render() {
return (
<div className="App">
<div ref="water">
{this.state.img && /* whatever you want to do with the image */ }
</div>
</div>
);
}
I'm not exactly sure what img resolves to, so don't know exactly what you'd put in the render function. If it's url string, it would be {this.state.img && <image src={this.state.img} />}
Related
Recently I've tried to create my own component using React Query with TinyMCE for React, but I noticed that every time I loose focus from TinyMCE editor's text area my request from React Query is sent again even though nothing has changed in my components (at least I think there is no need for rerender of the component).
Here you can see that every time I click into editor and after that outside of the editor the request is sent
I created project to simulate the problem. You can see that every time you focus and unfocus from the text area of the TinyMCE editor the request from React Query is sent. I tried to use useEffect to know if the provided callback is called multiple times as well, but the useEffect works as expected.
import React, { useEffect } from "react";
import {
QueryClient,
QueryClientProvider,
useQuery
} from "#tanstack/react-query";
import ReactDOM from "react-dom/client";
import { Editor } from "#tinymce/tinymce-react";
export default function MyEditor() {
return (
<div>
<Editor />
</div>
);
}
const fetchData = async () => {
console.log("Fetching data", new Date());
return await fetch("https://jsonplaceholder.typicode.com/posts/1").then((d) =>
d.json()
);
};
function App() {
useQuery(["api"], fetchData);
useEffect(() => {
console.log("This is going to be logged only once");
}, []);
return (
<form>
<h1>My editor</h1>
<MyEditor />
</form>
);
}
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById("container")).render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
These are my package versions:
{
"dependencies": {
"#tanstack/react-query": "4.3.9",
"#tinymce/tinymce-react": "4.2.0",
"react": "18.2.0",
"react-dom": "18.2.0"
}
}
I think it's because the editor renders an iframe, you can use the refetchOnWindowFocus option to avoid refetching:
useQuery(["api"], fetchData, { refetchOnWindowFocus: false })
or perhaps using the method to ignore iframe focus described in the same doc page
It works on codesandbox
I am using Gatsby with React and am trying to implement a Calendly booking system. It sort of works. The issue is on first load it gives me the error
TypeError: Cannot read property 'initInlineWidget' of undefined
seen here
If I refresh the page the Calendly Object loads and renders just fine.
I am wondering if there is something I can do in the useEffect to avoid this issue.
import React, { useEffect } from "react"
import Layout from "../components/layout"
const Calendly = styled.div`
height: 800px;
margin-top: 100px;
`
const IndexPage = ({ data }) => {
useEffect(() => {
window.Calendly.initInlineWidget({
url: "https://calendly.com/absolute-hardwood",
parentElement: document.getElementById("bookingjs"),
prefill: {},
utm: {},
})
}, [])
return (
<Layout>
<Calendly id="bookingjs" />
</Layout>
)
}
export default IndexPage
Here is how I am adding the Calendly script in my gatsby-confing.js
{
resolve: "gatsby-plugin-load-script",
options: {
src: "https://assets.calendly.com/assets/external/widget.js",
},
}
Marshall here from Calendly. Since you are using React and Gatsby, you can use the react-calendly package to load the inline embed on your site.
You will need to install the react-calendly package in your project, and then import the InlineWidget like this at the top of your file:
import { InlineWidget } from "react-calendly";
Then, you can use the component on your page:
<InlineWidget url="https://calendly.com/your_scheduling_page" />
I hope this helps! Further documentation can be found in the package readme on Github.
I have below code structure,
and my src/components/App.js look like this
import React, { Component } from 'react'
import { max_number } from '../helper'
class App extends Component {
render() {
return (
<div>
</div>
)
}
}
export default App
As you can see helper folder is the same level as components, but somehow I got error of Module not found: Can't resolve '../helper' in '/Users/james/Documents/react-demo/src/components'
helper.js is a directory you need to import from '../helper.js'
preferably rename the folder to helper
I'm having an issue using the AsyncTypeahead from the react-bootstrap-typeahead project, where it seems like my onSearch handler is not getting called. I can see the typeahead on the page, but when I type in it, handleSearch is not being executed and I don't see any console logging. Here's a short example:
import React, {PropTypes, Component} from 'react';
import AsyncTypeahead from 'react-bootstrap-typeahead';
class CustomTypeahead extends Component {
state = { results: [] }
handleSearch(event) {
console.log("Show me what you got")
// fetch data here and set state to results in a promise
// this.setState(results)
}
render() {
return (
<div>
<AsyncTypeahead
onSearch={this.handleSearch.bind(this)}
options={this.state.results}/>
</div>
)
}
}
Any suggestions or insights are really appreciated!!!
Fixed by using:
import { AsyncTypeahead } from 'react-bootstrap-typeahead';
instead of
import AsyncTypeahead from 'react-bootstrap-typeahead';
and updating to version ^1.0.0 for react-bootstrap-typeahead
Please bear with me because I am a javascript newbie, and just starting to learn react.
I am trying to make a small app but I keep getting an error that one of my files is not found... specifically this:
bundle.js:56 Uncaught Error: Cannot find module "./components/search_bar"
My file structure is that I have my index.js in a folder called src, then my search bar(search_bar.js) in a folder called components. I have triple checked the spelling on them but I continue to get this error.
This is my index.js
import SearchBar from './components/search_bar';
import React from 'react';
import ReactDOM from 'react-dom';
//Create a componant (some /HTML)
const API_KEY = 'AIzaSyC3Z3qTpvAacDLYEIxaueKflFJbWvdIHsw';
const App = () => {
return (
<div>
<SearchBar />
</div>
);
}
// Put that componant on the page (the DOM)
ReactDOM.render(<App />, document.querySelector('.container'));
And this is my search_bar.js
import React, { Component } from 'react';
class SearchBar extends Component {
contructor(props) {
super(props);
// when user updates the search bar this term will get updated.
this.state = { term: ''};
}
render() {
//update state
//use set state everywhere besides constructor!!
return (
<div>
<input onChange={event => this.setState({term: event.target.value})}
/>
Value of the input: {this.state.term}
</div>
);
}
}
export default SearchBar;
Any Ideas as to what I am doing wrong here?
Can you confirm the following directory structure?
my_project/src/index.js
my_project/src/components/search_bar.js
It seems like your current directory structure might instead look like this:
my_project/src/index.js, my_project/components/search_bar.js
AHHH I left an 's' out of constructor... so search_bar.js was unable to compile. I have been looking at this for about an hour now...