Javascript

Problems, solutions and everything in between.
Latest entries

React deconstruct a single prop whilst maintaining the other props

You may or may not know you can deconstruct props. In the shortest possible explanation, deconstructing allows you to extract information from an element and saving that in its own variable. For example, the below code would give me two variables "name" and "location" const Person = { name: 'Chris', location: 'UK'} const { name, location } = Person; Moving this on, you can deconstruct from within components. const functionalComponent = (Person) => {} // becomes const functionalComponent =…

indexOf always returning -1 in JavaScript

I have the below setup const myArr = [ {name: 'Chris'}, {name: 'Archie'} {name: 'John'}, {name: 'Paul'}, {name: 'Daniel'}, {name: 'Kyle'} ] let items = Object.keys(myArr.slice(0, 4)); let newItem = Math.floor(Math.random() * myArr.length); let item = items.indexOf(newItem); // returns -1 This is due to Object.keys returning string values and newItem is returned as an int. You need to convert the int "toString()" let newItem = Math.floor( Math.random() * myArr.length ).toString();

Adding Property Initializers To Your React/Babel For Cleaner Components

If you want to declare state like below without the use of a constructor state = { name: "Chris" } You need to add the ES7 feature babel-plugin-transform-class-properties. yarn add babel-plugin-transform-class-properties // .babelrc { "plugins": ["transform-class-properties"] }

React Not Compiling Spread/Rest Operator

If you're facing the error "Module build failed: SyntaxError: Unexpected token" when trying to use the spread operator. Chance are you're missing the Object rest spread transform which can be found here: https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/. Run: npm install --save-dev babel-plugin-transform-object-rest-spread OR yarn add babel-plugin-transform-object-rest-spread Then if you don't already have a .babelrc file, create one with the following. { "plugins":…

jQuery.ajax - Submit All Inputs In Form Without The Need To Manually Enter Them

Use serialize data : $("form").serialize() So your Ajax call might look something like this let ajax = new XMLHttpRequest(); let form = $(this); $.ajax({ url: form.attr('action'), type: form.attr('method'), data: form.serialize(), success: function (data) { const { success, message } = data; let response = this.querySelector('.response'); response.innerHTML = '' + message + ''; if (success) form.style.display = 'none' }, error: function (err) { console.warn('Error') console.warn(err) } });

JavaScript Operators To Improve Your Daily Productivity

Contents Spread Operator Spread Operator Expands an array into it's individual elements const food = ['pizza', 'chips', 'nuggets'] console.log(...food) // returns: pizza chips nuggets As use case would be with React and passing down the props, you may not necessary want to pass down everything individually so you could do something like return ( )

Document.cookie not working

If you're having trouble with "document.cookie" it's likely you're working locally and not on an apache server. opening "index.html" in your default browser will fail however "localhost:8080/index.html" will work. If you have PHP installed locally you can power up an apache server easily by running the following command php -S localhost:8080 The above command will start a server in the location that you ran the command. document.addEventListener("DOMContentLoaded", function(){ document.cookie =…

Webpack Compiling But Not Hot Reloading / Showing Any Changes

To solve this I quickly added publicPath to my webpack.config.js file. output: { path: path.join(__dirname, 'public', 'build'), publicPath: "/build/", filename: 'bundle.js' },

Show the whole current ‘state’ with React - JSON.Stringify

{JSON.stringify(this.state, null, 4)} Read more on JSON.stringify here { "success": false, "message": {}, "firstname": "", "surname": "", "tel": "", "email": "", "contact_message": "" }

[SOLVED]: Super expression must either be null or a function ReactJS

I had this problem when using a lower case "c" on component... Class Hello extends React.Component If this doesn't solve your issue, try updating your React version.

Fetch API

fetch('https://www.barberriley.com/api/some/url').then(function(res) { console.log(res); }).catch(function(error) { console.log(error); }); Adding headers to the call fetch('https://www.barberriley.com/api/some/url.json', { method: 'POST', mode: 'cors', redirect: 'follow', headers: new Headers({ 'Content-Type': 'text/plain' }) }).then(function() { /* handle response */ });

Submitting form via Ajax and handling response

$.ajax({ type: "POST", url: url, data: form.serialize(), success: function(data) { if(data == 'Success'){ $("p#response").text('Success, your message has been sent'); $("p#response").addClass( "contact-success" ); } else { $("p#response").text(data); } //console.log(data); } });

uncaught reference error require is not defined

Short answer here, make sure you call the correct file on index.html. I do everything in main.js and then compile into main.min.js, I was calling main.js when I should have been calling main.min.js This solved the problem when requiring .jsx files into a single js file. Hope this saves you a little bit of time. ps - I tried everything solving this, there may have been another solution but I also had to make sure I had the correct dependencies installed

Webpack no output file: How to debug and save a load of time

Webpack for some reason or another wouldn't render to the output file and I was convinced it was the "output" line on my webpack.config file, however after changing that I come to the realisation I was wasting my time. Simply running this command will save you a hell of a lot of time. webpack --display-error-details This told me exactly where my problem was and the fact I was trying to import a .scss file from a relative path rather than an absolute path was the gotcha in the end and it had…

Package.json default template

{ "name": "Project name", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "babel-core": "^6.17.0", "babel-loader": "^6.2.5", "babel-preset-es2015": "^6.16.0", "babel-preset-react": "^6.16.0", "react": "^15.3.2", "react-cookie": "^0.4.8", "react-dom": "^15.3.2", "react-modal": "^1.5.2", "webpack": "^1.13.2", "whatwg-fetch": "^2.0.1" }, "author": "", "license": "ISC" }

Webpack.config.js default template

let webpack = require('webpack'); module.exports = { context: __dirname, entry: "./main.js", watch:true, output: { path: __dirname + "/js", filename: "main.min.js" }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets: ['es2015', 'react'] } } ] }, plugins: [ new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }), new webpack.DefinePlugin({…

What does “NaN” mean in JavaScript?

What you declare a variable in Javascript it has an initial value of "undefined" until a value is set. When performing a mathematical equation on said variable you will be return "NaN" which stands for "Not a Number". var a; // undefined var b; var a + b; // NaN var a = 10; var b = 5; var a + b; // 15

JavaScript Basics: Count the words in a string

This is a quick function to count the words in a given string. <script> function wordCount(str){ return str.split(' ').length; } console.log(wordCount('Hello, how are you?')) </script>

Check if JavaScript is enabled

<noscript> <style> .heads-up{ color: #31708f; background-color: #d9edf7; border-color: #bce8f1; padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } </style> <div class="heads-up"> JavaScript is disabled </div> </noscript> There's no absolute fool proof way of checking JS, you can check cookies, meta refresh to another page etc, however this works best for me. If JS is disabled it will product the below output.