I would appreciate some advice on how to load jQuery in my React App that involves a simple form. What I want to achieve here is to add placeholder support for my React form inputs in IE9 (the lowest IE version supported by my app).
I use detect-browser to check and retrieve the browser version. If IE9, then load jQuery in my head tag and insert placeholders into my inputs using the well-known jQuery script from below.
The way I load jQuery now, I get the error SCRIPT5009: '$' for obvious reasons. What am I doing wrong here and how can I fix this? I have also tried import $ from 'jquery'; and then just removing the script that loads jquery from head but this doesn't fix my problem, i still get the same error from above.
Here is my code:
import React from 'react';
const browser = require('detect-browser');
class App extends React.Component {
constructor(props) {
super(props);
this.iePlaceholder = this.iePlaceholder.bind(this);
}
iePlaceholder() {
if(browser.name === 'ie' && browser.version === '9.0.0') {
const scriptJquery = document.createElement("script");
scriptJquery.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
document.head.appendChild(scriptJquery);
const placeholdersIeScript = `
$(document).ready(function() {
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
});
`
const script = document.createElement("script");
script.type = "text/javascript";
script.innerHTML = placeholdersIeScript;
document.head.appendChild(script);
}
}
componentWillMount() {
this.iePlaceholder();
}
render() {
return (
<div>
<h1>A title</h1>
<form>
<input id="myInput"
type="text"
placeholder="MyPlaceholder"
/>
</form>
</div>
);
}
}
export default App;
You could do something as simple as const $ = require('jquery');
after installing jquery with npm, then just run the script rather than trying to inject it as you're doing.
Another approach would be to use webpack. In your webpack config file, you can add a plugin using this syntax:
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
]
That will automatically replace $ references in your code with jquery, although it's just a shortcut to avoid using const $ = require('jquery');
elsewhere in your code.