How to use materialize-css with React? - reactjs

I have a Meteor/React project, using ES6 modules. I've installed materialize-css using npm, but I'm not sure how to actually use the Materialize classes in my JSX code. What am I supposed to import from materialize-css? Or do I just have to include the CSS in my main index.html file?
I mostly want it for the grid system, as I'll be using material-ui for the actual UI components.

Since I use CSS Modules, importing materialize css would scope it to that particular component. So I did the following
Step 1) install materialise
npm install materialize-css#next
Step 2) in index.html
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-alpha.3/css/materialize.min.css">
Step 3) import materialise.js in whichever component its needed
for e.g. in SomeComponent.js (for e.g. if this is about a sidenav)
import React from 'react';
import M from 'materialize-css';
....
// ref can only be used on class components
class SomeComponent extends Component {
// get a reference to the element after the component has mounted
componentDidMount(){
M.Sidenav.init(this.sidenav);
}
render(){
return (
<ul className={this.props.classes}
ref={ (sidenav) => {this.sidenav = sidenav} }
id={this.props.id}>
// menuItems
</ul>
)
}
}
just a beginner, so I would appreciate any comments on downsides of this method

With NPM:
Step 1) Install materialize
npm install materialize-css#next
Check the materialize documentation for any updates. Don't miss the #next at the end. The installed version will be something like: ^1.0.0-rc.2 or ^1.0.0-alpha.4
Step 2) Import materialize JS:
import M from 'materialize-css'
Or if that doesn't work you can try import M from 'materialize-css/dist/js/materialize.min.js'
Step 3) Import materialize CSS:
In index.html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
OR in javascript
import 'materialize-css/dist/css/materialize.min.css'
In order for the css import to work, you would need a css loader. Note that this loader is already included in projects built using create-react-app so you don't need the next steps. If instead, you are using custom webpack config, then run:
npm install --save-dev style-loader css-loader
Now add css-loader and style-loader in webpack config
const path = require("path");
module.exports = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: path.join(__dirname, "build")
},
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /.js$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["env", "react"]
}
}
}
]
}
}
Now you can initialize components individually, or all at once using M.AutoInit();
Step 4) Import materialize icons:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
With CDN:
Add the following in your HTML file.
<!-- Materialize CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/css/materialize.min.css">
<!-- Materialize JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<!-- Materialize Icons -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
Then, in the webpack config, add externals: https://webpack.js.org/configuration/externals/

You can use https://react-materialize.github.io/#/, why to reinvent the wheel.
installation react-materialize
npm install react-materialize
Usage
import {Button, Icon} from 'react-materialize'
export default () => (
<Button waves='light'>
<Icon>thumb_up</Icon>
</Button>
)
Sample
https://github.com/hiteshsahu/react-materializecss-template
Screenshot

There are several ways of using Materialize CSS in ReactJS. However, I always use the following easiest one.
Here you can use Materialize CSS classes just like your HTML site using only ClassName with tags.
1 ) Install Materialize CSS for ReactJS using NPM.
npm install materialize-css#next
2 ) Then import the minified materialize CSS file to index.js file.
import 'materialize-css/dist/css/materialize.min.css'
3 ) Now if you want to use google icons add the following codes in your public / index.html file.
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
4 ) Finally to use Javascript events on input forms or other places add the following codes in your public / index.html file.
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
N.B. => Since all files need to go through the index.js file, so importing your minified Materialize CSS to index.js once is enough. Otherwise, you need to import these CSS files to all your js files.
That's enough to prepare your ReactJS folder for up and running with Materialize CSS. Happy Coding.

as for the question, i think just npm i materialize-css and then
import "materialize-css/dist/css/materialize.min.css";
import "materialize-css/dist/js/materialize.min.js";
should do the job.
I wanted to share a problem I faced and how i solved it.
I wanted to get materialbox to work and here is how i did it
import React, { Component } from "react";
import M from "materialize-css/dist/js/materialize.min.js";
class Image extends Component {
constructor(props) {
super(props);
this.imageRef = React.createRef();
}
onLoad = () => {
M.Materialbox.init(this.imageRef.current);
};
render() {
return (
<img
src="..."
alt="..."
className="materialboxed"
ref={this.imageRef}
onLoad={this.onLoad}
/>
);
}
}
export default Image;
an interesting thing to note - it didnt work when i was trying M.init inside componentDidMount maybe because the image doesnt load by the time the call to componentDidMount is made.
react-materialize will surely make things easier if you want to use a lot of JS using components like modals etc.

There are possible ways that I can recommend to use:
One way is just include your stylesheet file in index.html and use
className property in your React components just like this.
var myDivElement = <div className="foo" />;
ReactDOM.render(myDivElement, document.getElementById('example'));
Another way is to bundle all your stylesheeets in one stylesheet file and to use them as previous one.
One option could be to use webpack. By using webpack, it is possible to use embedded stylesheets in jsx files just by requiring stylesheet that you want to include.
require("./stylesheet.css")
To examine in detail webpack stylesheet option: http://webpack.github.io/docs/stylesheets.html
Also see JedWatson's classnames repo for conditional className usage.
https://github.com/JedWatson/classnames

Solution Without index.html
From react-materialize - Installation
npm install materialize-css
npm install react-materialize
In your App.js or App.jsx add
import "materialize-css/dist/css/materialize.min.css";
import "materialize-css/dist/js/materialize.min.js";
Usage Examples:
Example 1
import React from "react";
import { Button } from "react-materialize";
export default function CustomMediaBox() {
return <Button> Click Me </Button>;
);
}
Example 2
import React from "react";
import { MediaBox } from "react-materialize";
export default function CustomMediaBox() {
return (
<MediaBox
options={{
inDuration: 275,
onCloseEnd: null,
onCloseStart: null,
onOpenEnd: null,
onOpenStart: null,
outDuration: 200
}}
>
<img
alt=""
src="https://materializecss.com/images/sample-1.jpg"
width="650"
/>
</MediaBox>
);
}
Optionally - Adding Icons
Although not required, if you want to use google icons, add the following to your App.css or any .css file imported from the App.js or App.jsx
#import url('https://fonts.googleapis.com/icon?family=Material+Icons');
Note
If you get an error like this:
./node_modules/react-materialize/lib/Breadcrumb.js
Module not found: Can't resolve 'classnames' in '/Users/artiomlk...
npm install classnames

Inorder to address the concern of bundle size, the easiest way to use it is as follows:
Include the CDN links in your index.html file
Initialize M in your React Component's constructor this.M = window.M
All the other required initializations in case of Modals and other Materialize Components can be done as mentioned in their Documentation using this.M
I like to do those initialization in the componentDidMount lifecycle method.
When unmounting i.e. inside componentWillUnmount, i use the destroy() method on the instances of initialized Materialize Components.

Install Materialize
npm i materialize-css#next
Initialize
import React, { useEffect } from 'react';
import 'materialize-css/dist/css/materialize.min.css';
import M from 'materialize-css/dist/js/materialize.min.js';
function App() {
useEffect(() => {
M.AutoInit();
},[])
return (
<div className="App">
// content...
</div>
);
}

You can copy into "imports" folder and add by
import '../imports/stylesheets/materialize.min.css';
or use this for LESS example
#import '{}npm-package-name/stylesheets/...';

These answers didn't satisfy my biggest concern which was bundle size and importing a ton of code in order to use a few components. I've written up a solution here that includes code splitting and an easy compilation step.
The key points are:
Compile base JS files (there are 4)
Ensure the base JS is included before your imports / bundler runs
Change the CSS imports to only what you need
Run materialize.scss through your bundler if it supports Sass or run the compilation step to get a minified css file.
Import individual components and activate them manually
Read post for more details.

Use CDN:
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
Then const M = window.M; to do initialization.

I don't know am I too late to put this answer.
You can use componentDidMount like this video
However, It does not use react-hooks. You'd better use react hooks (useEffects)

How to use materialize-css with React with icons and other js features
yarn add materialize-css#next --save or npm install materialize-css#next --save
yarn add install material-icons or npm install material-icons
3.Kindly import the following like this ;
snap
import 'materialize-css/dist/css/materialize.min.css';
import 'materialize-css/dist/js/materialize';
import 'material-icons/iconfont/material-icons.css'
function App() {
return (
<div className="App">
<nav className="nave-wrapper">
<div className="container">
Logo
<ul className="right">
<li>Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</nav>
<div className="container">
<i class="material-icons">add</i>
<i class="large material-icons">insert_chart</i>
<div class="row">
<form class="col s12">
<div class="row">
<div class="input-field col s6"/>
<i class="material-icons prefix">account_circle</i>
<input id="icon_prefix" type="text" class="validate"/>
<label for="icon_prefix">First Name</label>
</div>
<div class="input-field col s6">
<i class="material-icons prefix">phone</i>
<input id="icon_telephone" type="tel" class="validate"/>
<label for="icon_telephone">Telephone</label>
</div>
</form>
</div>
</div>
</div>
);
}
export default App;

Install Materialize
npm i materialize-css#next
npm install react-materialize
Initialize
import React, { useEffect } from 'react';
import 'materialize-css/dist/css/materialize.min.css';
import M from 'materialize-css/dist/js/materialize.min.js';
const App = () => {
useEffect(() => {
// Init Materialize JS
M.AutoInit();
});
return (
<div className="App">
// content...
</div>
);
}
export default App;

Install materialize css via npm through npm install materialize-css#next
Add this code import 'materialize-css/dist/css/materialize.min.css' to your App.js file to add materialize globally so you don't have to call materialize in individual components.
Call materialize classes like so <button className="waves-effect waves-light btn blue darken-4"><i class="material-icons">add</i></button>
For materialize fonts add <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> to your index.html in the public folder and call the icons anywhere
Side note: I am using React 18.2.0. Also, I can send you my github code for you to go through.

Related

Add React app build to my existing website div

Is it possible to add a build index.html of a React app to a div in my HTML/ColdFusion website?
I built a chatbot in React using hooks.
Bellow is my App.js which imports my ChatBot.js component.
import './App.css';
import MyChatBot from './ChatBot';
function App() {
return (
<div className="App">
<MyChatBot/>
</div>
);
}
export default App;
It is working. I have a ColdFusion/HTML website where I would like to include this "chatbot" or the generated index.html from npm run build to a div
<!-- ColdFusion Website here --->
<div id="myChatBot"></div>
The idea is to have the React application inside that div. Is it possible?
Thank you.
Yes, you can. You just need to pass the element ( where you want to mount the react app ) to ReactDOM.render method. Then bundle your react app using a bundler, say webpack, and include that bundle via script tag or via the current build process in your app's html.
HTML
<!-- Website Markup --->
<div id="myChatBot"></div>
<!-- Include React bundle --->
<script src="bundle.js"></script>
React
import ReactDOM from "react"
import App from "./App"
ReactDOM.render(<App/>, document.getElementById("myChatBot"))
Hope this is helpful to you: https://reactjs.org/docs/add-react-to-a-website.html
Gist of it is you have import the React scripts and render it to that id:
const domContainer = document.getElementById('myChatBot');
ReactDOM.render(e(LikeButton), domContainer);

react-fontawesome not displaying icons

I'm attempting to using react-fontawesome and implementing it in what seems to me to be exactly the same as the readme: https://github.com/danawoodman/react-fontawesome/blob/master/readme.md
import React from 'react';
import FontAwesome from 'react-fontawesome'
...
export default class ComponentName extends React.Component {
render() {
return (
<div>
<div>
<span>
<FontAwesome
className='super-crazy-colors'
name='rocket'
size='2x'
spin
style={{ textShadow: '0 1px 0 rgba(0, 0, 0, 0.1)' }}
/>
SOME TEXT
</span>
</div>
...
</div>
)
}
}
But I'm not seeing an icon in the DOM. Although I do see in the Chrome Dev Tools:
<span style="text-shadow:0 1px 0 rgba(0, 0, 0, 0.1);" aria-hidden="true" class="fa fa-rocket fa-2x fa-spin super-crazy-colors" data-reactid=".0.$/=11.0.0.$/=10.$/=10.$/=10"></span>
which I feel like should be a <i> tag. I tried changing the <span>...</span> to an <i>...</i> in "edit as HTML" in the dev tools and the icon still didn't show.
I have add-module-exports in my plugins and stage-2 in my presets in my webpack.config.
Can anyone tell me if I'm missing something? Do I need some other package other than react-fontawesome to make this work? Do I need to import the standard font-awesome.css or load a font-awesome CDN? Any help would be greatly appreciated, thanks!
I had the same problem. Read their Readme.md, and you see that there is this note:
Note: This component does not include any of the Font Awesome CSS or fonts, so you'll need to make sure to include those on your end somehow, either by adding them to your build process or linking to CDN versions.
So the most simple way is to link to the fontawesome cdn in your html.
<head>
<meta charset="UTF-8">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css" rel="stylesheet" integrity="sha384-
wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous">
</head>
Run npm install font-awesome --save
In your index.js or App.js or YourComponent.js, import the minified CSS file.
import 'font-awesome/css/font-awesome.min.css';
As the other answers mention, you need to include the icons in your page somehow. Check out the react-fontawesome example here:
https://github.com/danawoodman/react-fontawesome/blob/master/examples/index.html
You can see that the developer has included the font-awesome CSS on line #5.
On a separate note, Font Awesome v5 has been released, and you should consider moving to it. Read relevant docs here:
https://www.npmjs.com/package/#fortawesome/react-fontawesome
To use v5:
Install dependencies:
$ npm i --save #fortawesome/fontawesome
$ npm i --save #fortawesome/react-fontawesome
$ npm i --save #fortawesome/fontawesome-free-solid
Your component can then use icons like so:
import ReactDOM from 'react-dom';
import FontAwesomeIcon from '#fortawesome/react-fontawesome'
import { faCoffee } from '#fortawesome/fontawesome-free-solid'
const element = (
<FontAwesomeIcon icon={faCoffee} />
)
ReactDOM.render(element, document.body);
You can also build a library of commonly used icons in your app, for easy reference. Check out working code here: https://codesandbox.io/s/8y251kv448
More details about the library function available here:
https://www.npmjs.com/package/#fortawesome/react-fontawesome#build-a-library-to-reference-icons-throughout-your-app-more-conveniently
The only example I got working that actually seems up-to-date and didn't throw "can't resolve 'react' errors:
https://scotch.io/tutorials/using-font-awesome-5-with-react
import React from "react";
import { render } from "react-dom";
// get our fontawesome imports
import { faHome } from "#fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
// create our App
const App = () => (
<div>
<FontAwesomeIcon icon={faHome} />
</div>
);
// render to #root
render(<App />, document.getElementById("root"));
Font Awesome now has an official React component that’s available to use their icons in your React applications.
Step 1 :
you must install 3 important packages in your project using a package manager like npm:
npm i --save #fortawesome/fontawesome-svg-core
npm install --save #fortawesome/free-solid-svg-icons
npm install --save #fortawesome/react-fontawesome
Step 2 :
if you're planning on styling the icons you must download these two extra packages :
npm install --save #fortawesome/free-brands-svg-icons
npm install --save #fortawesome/free-regular-svg-icons
Step 3:
Once you’ve installed all the packages you need for your project, now you can use the icons.
Import this packages in your component like this:
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
After that you can import an icon into your component like this (example
using an icon with the class as "fas fa-atom")
import { faAtom } from '#fortawesome/free-solid-svg-icons'
P.S : you can import multiple icons in one import with adding a coma between
each one.
Step 4 :
use the imported icons
const element = <FontAwesomeIcon icon={faAtom} />
SOURCE : https://fontawesome.com/v5.15/how-to-use/on-the-web/using-with/react
This seems to work perfectly for React
Installation:
$ yarn add #fortawesome/fontawesome-svg-core #fortawesome/free-solid-svg-icons #fortawesome/react-fontawesome
Usage:
import ReactDOM from 'react-dom'
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faCoffee } from '#fortawesome/free-solid-svg-icons'
const element = <FontAwesomeIcon icon={faCoffee} />
ReactDOM.render(element, document.body)
Font Awesome 5 React
As #Alee pointed out Fontaweome fonts aren't included in the package. You will have to import it yourself.
Install npm font-awesome package. If you use npm run npm install font-awesome --save or if you use yarn then run yarn add font-awesome
Now you just have to import font-awesome.less under less directory by writing import 'font-awesome/less/font-awesome.less'
Now you should see your icons working :)
import fontawesome styles from the package itself without loading any external css:
import "#fortawesome/fontawesome-svg-core/styles.css"; // import Font Awesome CSS
import { config } from "#fortawesome/fontawesome-svg-core";
config.autoAddCss = false; // Tell Font Awesome to skip adding the CSS automatically since it's being imported above
See article to get more info
copy and paste in your html ...
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
NEXT JS - Import styles this way if you are using NEXT jS
import '../node_modules/#fortawesome/fontawesome-svg-core/styles.css'
I suspect that you have not yet imported the CSS that FontAwesome needs - download the minified CSS file from FontAwesome's Web site and import it into your app.scss file or wherever else you're importing other stylesheets.
The react-fontawesome library is helping you create elements with class names like 'up-arrow', but without the stylesheet, your project will not know that there are icons corresponding to those classes.
Better to install everything all at once and then only import the icon you want,
npm i --save #fortawesome/fontawesome-svg-core #fortawesome/free-solid-svg-icons #fortawesome/react-fontawesome #fortawesome/free-brands-svg-icons #fortawesome/free-regular-svg-icons
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faSpinner } from '#fortawesome/free-solid-svg-icons';
make sure to import the icon from the exact pack, you can use ctrl + space to use the power of suggections to fiding icons and for changing pack when your importing icon.
Make sure that you have installed the Font Awesome package correctly
using a package manager like npm or yarn. You can install it by
running the following command in your project directory:
npm install --save #fortawesome/fontawesome-free
Check if you have imported the required font awesome files in your
project. Make sure to import the necessary stylesheets and the icons
library in your project files. You can do this by adding the
following code to your main index.js file:
import '#fortawesome/fontawesome-free/css/all.css';
import { library }from '#fortawesome/fontawesome-svg-core';
import { fab } from '#fortawesome/free-brands-svg-icons';
import { fas } from'#fortawesome/free-solid-svg-icons';
Ensure that the icon name and style properties are set correctly.
You can use the FontAwesomeIcon component from the
#fortawesome/react-fontawesome package to display icons in your
project. For example, you can display a faUser icon with a solid
style using the following code:
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faUser } from '#fortawesome/free-solid-svg-icons';
<FontAwesomeIcon icon={faUser} style={{color: 'black'}} />
If the above steps do not work, try clearing your browser cache and
restarting your development server.
If the issue persists, you may want to check the Font Awesome
documentation and GitHub repository for additional help and support
.
Try adding
<script src='https://use.fontawesome.com/3bd7769ce1.js'></script>
to your main index.html within your react project.

What do I misunderstand about import in ES6?

I've done very simple markdown previewer using mark library in React. At first I did it by adding scripts to my Index.html in the
<body>
<div id="root"></div>
<script src="https://unpkg.com/react#latest/dist/react.js">
<script src="https://unpkg.com/react-dom#latest/dist/react-dom.js">
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.6/marked.min.js"></script>
<script type="text/babel" src="script.js" ></script>
</body>
Everything worked fine, but when I removed strings react.js and react-dom.js, and added them to the script.js as below, I saw an error in console:
import React from "react.min"
import ReactDOM from "react-dom.min"
class Input extends React.Component {
constructor(props) {
super(props);
this.state = {
_text: "",
};
}
handleChange(e) {
this.setState({
_text: marked(e.target.value)
});
}
createMarkup() {
let outPutVal = this.state._text ? this.state._text : this.state._init;
return {
__html: outPutVal
};
}
render() {
return (<form className="headDiv">
<textarea onChange={this.handleChange.bind(this)}
placeholder="Remember, be nice!"
id="inputText" rows="25" cols="100">{this.state._text}</textarea>
<output id="outputText" dangerouslySetInnerHTML={this.createMarkup()} />
</form>);
}
}
ReactDOM.render(<Input/>, document.getElementById("root"));
When using JS modules, Babel only handles the translation of import statements into CommonJS require calls - you still need a module loader of some kind to actually handle linking them all up.
Some examples of tools you could use for this are:
Webpack
Browserify
SystemJS
JSPM
That said, since you have the libraries included as script tags in your page, just removing the imports entirely would probably fix your issue - that approach really doesn't scale well though, so I encourage you to look into the above tools!
After installing with npm, you'd normally just import as follows (no .min):
import React from 'react';
import ReactDOM from 'react-dom';
You might want to consider a boilerplate like create-react-app - brilliant for getting started with an environment to focus on learning react.
create-react-app
In order to use import within your JSX code you need to use either webpack or browserify . Also you need to install these modules using npm before importing them
In order to install them run
npm install -S react-dom
npm install -S react
You can later import them as
import React from 'react';
import ReactDOM from 'react-dom';
Here is an easy tutorial that you can follow to set up your react code with webpack

React with react-bootstrap-4

I'm trying to get my hands on writing my first component using bootstrap 4.
import React,{Component} from 'react';
import {Button} from 'react-bootstrap-4';
class TextField extends Component {
constructor(props){
super(props);
}
render() {
return (
<Button bsStyle="primary" bsSize="large">Default</Button>
);
}
}
export default TextField;
In my index.js I call it as follows:
import React, {Component} from 'react';
import ReactDOM from "react-dom";
import TextField from './components/custom/text_field';
class App extends Component{
constructor(props){
super(props);
}
render(){
return (
<div>
Helo World1
<br/>
<TextField id="test" />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
When I run the app I don't get any errors but the button is not looking like its suppose to
Am I missing something?
You're responsible for including Bootstrap's CSS yourself with react-bootstrap, which react-bootstrap-4 is a (temporary) fork of.
As per its Getting Started guide:
Because React-Bootstrap doesn't depend on a very precise version of Bootstrap, we don't ship with any included css. However, some stylesheet is required to use these components. How and which bootstrap styles you include is up to you, but the simplest way is to include the latest styles from the CDN.
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css">
For more advanced use cases you can also use a bundler like Webpack or Browserify to include the css files for you as part of your build process but that is beyond the scope of this guide.
You would need to do the equivalent for Bootstrap 4.
by including Bootstrap 4 via CDN as above you only get css and any JS dependent component will not work. I've been facing this problems with React on Meteor.js.
What I did was to npm install:
"bootstrap": "^4.0.0-alpha.6",
"tether": "^1.4.0" // Tether is required by bootstrap.js
Import the css through the main js file:
import 'bootstrap/dist/css/bootstrap.css'
The only way I got full Bootstrap with JS was to grab a copy of bootstrap.js into my libs folder (any front end folder), modify it to import Tether at the top:
import tether from 'tether'
global.Tether = tether
For some reasons I couldn't find another way to resolve the Tether dependency.
Meteor does its own minification so I was not really bothered with the .min.js, however, you cannot import tether into a minified bootstrap.js.
Like many others I am waiting for a more "final" release of bootstrap 4 and possibly a simple npm i bootstrap --save procedure.

How to include a Font Awesome icon in React's render()

Whenever I try to use a Font Awesome icon in React's render(), it isn't displayed on the resulting web page although it works in normal HTML.
render: function() {
return <div><i class="fa fa-spinner fa-spin">no spinner but why</i></div>;
}
Here is an live example: http://jsfiddle.net/pLWS3/
Where is the fault?
If you are new to React JS and using create-react-app cli command to create the application, then run the following NPM command to include the latest version of font-awesome.
npm install --save font-awesome
import font-awesome to your index.js file. Just add below line to your index.js file
import '../node_modules/font-awesome/css/font-awesome.min.css';
or
import 'font-awesome/css/font-awesome.min.css';
Don't forget to use className as attribute
render: function() {
return <div><i className="fa fa-spinner fa-spin">no spinner but why</i></div>;
}
React uses the className attribute, like the DOM.
If you use the development build, and look at the console, there's a warning. You can see this on the jsfiddle.
Warning: Unknown DOM property class. Did you mean className?
https://github.com/FortAwesome/react-fontawesome
install fontawesome & react-fontawesome
$ npm i --save #fortawesome/fontawesome
$ npm i --save #fortawesome/react-fontawesome
$ npm i --save #fortawesome/fontawesome-free-solid
$ npm i --save #fortawesome/fontawesome-free-regular
$ npm i --save #fortawesome/fontawesome-svg-core
then in your component
import React, { Component } from 'react';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faCheckSquare, faCoffee } from '#fortawesome/fontawesome-free-solid'
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<h1>
<FontAwesomeIcon icon={faCoffee} />
</h1>
</div>
);
}
}
export default App;
npm install --save-dev #fortawesome/fontawesome-free
in index.js
import '#fortawesome/fontawesome-free/css/all.min.css';
then use icons like below :
import React, { Component } from "react";
class Like extends Component {
state = {};
render() {
return <i className="fas fa-heart"></i>;
}
}
export default Like;
You can also use the react-fontawesome icon library. Here's the link: react-fontawesome
From the NPM page, just install via npm:
npm install --save react-fontawesome
Require the module:
var FontAwesome = require('react-fontawesome');
And finally, use the <FontAwesome /> component and pass in attributes to specify icon and styling:
var MyComponent = React.createClass({
render: function () {
return (
<FontAwesome
className='super-crazy-colors'
name='rocket'
size='2x'
spin
style={{ textShadow: '0 1px 0 rgba(0, 0, 0, 0.1)' }}
/>
);
}
});
Don't forget to add the font-awesome CSS to index.html:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
The simplest solution is:
Install:
npm install --save #fortawesome/fontawesome-svg-core
npm install --save #fortawesome/free-solid-svg-icons
npm install --save #fortawesome/react-fontawesome
Import:
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import { faThumbsUp } from '#fortawesome/free-solid-svg-icons';
Use:
<FontAwesomeIcon icon={ faThumbsUp }/>
npm install --save font-awesome
import 'font-awesome/css/font-awesome.min.css';
then
<i className="fa fa-shopping-cart" style={{fontSize:24}}></i>
<span className="badge badge-danger" style={{position:"absolute", right:5, top:5}}>number of items in cart</span>
In case you are looking to include the font awesome library without having to do module imports and npm installs, put this in the head section of your React index.html page:
public/index.html (in head section)
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
Then in your component (such as App.js) just use standard font awesome class convention. Just remember to use className instead of class:
<button className='btn'><i className='fa fa-home'></i></button>
You need to install the package first.
npm install --save react-fontawesome
OR
npm i --save #fortawesome/react-fontawesome
Don't forget to use className instead of class.
Later on you need to import them in the file where you wanna use them.
import 'font-awesome/css/font-awesome.min.css'
or
import FontAwesomeIcon from '#fortawesome/react-fontawesome'
After struggling with this for a while I came up with this procedure (based on Font Awesome's documentation here):
As stated, you'll have to install fontawesome, react-fontawesome and fontawesome icons library:
npm i --save #fortawesome/fontawesome-svg-core
npm i --save #fortawesome/free-solid-svg-icons
npm i --save #fortawesome/react-fontawesome
and then import everything to your React app:
import { library } from '#fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faStroopwafel } from '#fortawesome/free-solid-svg-icons'
library.add(faStroopwafel)
Here comes the tricky part:
To change or add icons, you'll have to find the available icons in your node modules library,
i.e.
<your_project_path>\node_modules\#fortawesome\free-solid-svg-icons
Each icon has two relevant files: .js and .d.ts, and the file name indicates the import phrase (pretty obvious...), so adding angry, gem and check-mark icons looks like this:
import { faStroopwafel, faAngry, faGem, faCheckCircle } from '#fortawesome/free-solid-svg-icons'
library.add(faStroopwafel, faAngry, faGem, faCheckCircle)
To use the icons in your React js code, use:
<FontAwesomeIcon icon=icon_name/>
The icon name can be found in the relevant icon's .js file:
e.g. for faCheckCircle look inside faCheckCircle.js for 'iconName' variable:
...
var iconName = 'check-circle';
...
and the React code should look like this:
<FontAwesomeIcon icon=check-circle/>
Goodluck!
as 'Praveen M P' said you can install font-awesome as a package. if you have yarn you can run:
yarn add font-awesome
If you don't have yarn do as Praveen said and do:
npm install --save font-awesome
this will add the package to your projects dependencies and install the package in your node_modules folder. in your App.js file add
import 'font-awesome/css/font-awesome.min.css'
Alexander's answer from above really helped me out!
I was trying to get social accounts icons in the footer of my app I created with ReactJS so that I could easily add a hover state to them while also having them link my social accounts. This is what I ended up having to do:
$ npm i --save #fortawesome/fontawesome-free-brands
Then at the top of my footer component I included this:
import React from 'react';
import './styles/Footer.css';
import FontAwesomeIcon from '#fortawesome/react-fontawesome';
import {faTwitter, faLinkedin, faGithub} from '#fortawesome/fontawesome-free-brands';
My component then looked like this:
<a href='https://github.com/yourusernamehere'>
<FontAwesomeIcon className ='font-awesome' icon={faGithub} />
</a>
Worked like a charm.
Personally, I found react-fontawesome to be unwieldy because of the way it requires each icon to be individually imported. If you would like to use Font Awesome version 5 with React without using react-fontawsome, you can do it as follows:
Download the fontawesome free package from font awesome themselves here: https://fontawesome.com/how-to-use/on-the-web/setup/hosting-font-awesome-yourself
Create a directory 'fontawesome' in the 'public' directory of your react app.
Copy the 'css' and 'webfonts' directories from the downloaded zip into this folder.
Add the following line to the 'head' tag of your 'index.html' file:
<link href="%PUBLIC_URL%/fontawesome/css/all.css" rel="stylesheet">
You can now use Font Awesome icons in the usual way:
<i className="fas fa-globe-europe"></i>
I was experienced this case; I need the react/redux site that should be working perfectly in production.
but there was a 'strict mode'; Shouldn't lunch it with these commands.
yarn global add serve
serve -s build
Should working with only click the build/index.html file.
When I used fontawesome with npm font-awesome, it was working in development mode but not working in the 'strict mode'.
Here is my solution:
public/css/font-awesome.min.css
public/fonts/font-awesome.eot
*** other different types of files(4) ***
*** I copied these files for node_module/font-awesome ***
*** after copied then can delete the font-awesome from package.json ***
in public/index.html
<link rel="stylesheet" href="%PUBLIC_URL%/css/font-awesome.min.css">
After all of above steps, the fontawesome works NICELY!!!
If someone wants to do it via the Official documentation. Here is how I did and what I understood.
Install the library as mentioned on font awesome page using npm or yarn for example in general I used these
npm i --save #fortawesome/fontawesome-svg-core
npm install --save #fortawesome/free-solid-svg-icons
npm install --save #fortawesome/react-fontawesome
You need two import library from '#fortawesome/fontawesome-svg-core' if you want to use in general or globally, it provides the access to the icons everywhere in your project.
import { library } from '#fortawesome/fontawesome-svg-core';
To use the icons you need to import them based on the npm or yarn library you have installed. I would recommend importing this in App.js where it will be easily visible. Like If I was using a free-tier shopping cart icon and it was solid you can import like below (if you are not sure if its solid, regular, etc or what library just click on the icon it will list out the different versions and based on the icon you like you can import the library for react).
import { faShoppingCart } from '#fortawesome/free-solid-svg-icons';
for adding the icon name I would recommend writing the import statement and library and then precede with fa and start typing the name it will auto-recommend as soon as you type (checked in VSCode) which will make it less complicated to find.
You need to add the icons in the library for making it accessible globally in your project separated by a comma
library.add( faCheckSquare, faAmbulance, faShoppingCart);
After which you can import the following component
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
and use it like below wherever you need the icon. For the name, it's the same as listed on the style class on the FontAwesome site, for the icons. eg: shopping cart is listed as shopping-cart
<FontAwesomeIcon icon="shopping-cart" />
It should work now after this.
Checkout react icons pretty dope and worked well.
In my case I was following the documentation for react-fontawesome package, but they aren't clear about how to call the icon when setting the icons into the library
this is was what I was doing:
App.js file
import {faCoffee} from "#fortawesome/pro-light-svg-icons";
library.add(faSearch, faFileSearch, faCoffee);
Component file
<FontAwesomeIcon icon={"coffee"} />
But I was getting this error
Then I added the alias when passing the icon prop like:
<FontAwesomeIcon icon={["fal", "coffee"]} />
And it is working, you can find the prefix value in the icon.js file, in my case was: faCoffee.js
For Font Awesome v6.x.x
Fontawesome provides three ways to use its icons.
After considering ease of usage and bundle size. The below method looks best.
yarn add #fortawesome/fontawesome-svg-core
# free icons styles
yarn add #fortawesome/free-solid-svg-icons
yarn add #fortawesome/free-regular-svg-icons
yarn add #fortawesome/react-fontawesome#latest
import icons that you want.
import { faClipboard } from "#fortawesome/free-solid-svg-icons";
import { faClipboard as farClipboard } from "#fortawesome/free-regular-svg-icons";
Note: if you need a Solid icon you need to import it from #fortawesome/free-solid-svg-icons and if you need a Regular icon you need to import it from #fortawesome/free-regular-svg-icons
Prefix regular icons with far instead of fa as a convention
Usage:
<p>
This is a free Solid Icon <FontAwesomeIcon icon={faClipboard} />
</p>
<p>
This is a free Regular Icon <FontAwesomeIcon icon={farClipboard} />
</p>
Note:
As you search for icons in Fontawesome documentation and copy the code you will get something as below. However, you need to change the icon prop to the above-mentioned value for the icon to display.
<FontAwesomeIcon icon="fa-solid fa-clipboard" />
Here is the CodeSandbox for the above-mentioned snippets.
Refer to official Docs for more info.
PS: You can only use Free Solid, and Free Regular icons under the free plan.
Here is the list of icons that are available under free plan.

Resources