How to use styles in Remix

How to apply CSS styles in Remix


In Reactjs and Nextjs we usually use module bases styles. Remix has its own way for handling style sheets.

links

By defining and expoerting a links funtion in any component, route, Remix will apply those styles to that file. Go head and use those classes.

I gusess that , we can use multipple style sheets since the links functions return an array of style object.

import React from "react";
import styles from "./404.css";
export const links = () => {
  return [
    {
      rel: "stylesheet",
      href: styles,
    },
  ];
};
export default function NF() {
  return (
    <div>
      <div>
        <div>
          <h3>Oops! Page not found</h3>
          <h1>
            <span>4</span>
            <span>0</span>
            <span>4</span>
          </h1>
        </div>
        <h2>we are sorry, but the page you requested was not found</h2>
      </div>
    </div>
  );
}```

Wonder how Links works? In the root(root.jsx) the Links component included so no need to worry about it.

How to add Emoji ๐Ÿ˜ to Draft-js in React

How to add Emojis to draft-js editor using plugin in React


Draft-js is Javascript Editor framework that featured in Facebook and it is an open source project which maintained by Facebook. It has larger user base compared to other. Draft-js was a complete framework for creating Ritch text editors and social interactions.

Plugin

Draft-js Plugins allow us to quickly add features such as tool bars , social mentions.

It is a React Plugin Architecture for Draft.js

Emoji Plugin ๐Ÿ’

The Emoji (๐Ÿ˜Š) plugin allow us add emojis to social interaction. This plugin allow use pick and emoji of our choice by pressing :.

Let’s install create a react project

npx create-react-app dracft-editor 

In the project add dependecies as follows

npm install @draft-js-plugins/editor
npm install @draft-js-plugins/emoji

We are ready to build our component. Using the Editor component we can use Editor in our app. The Editor state will manage the state of the app.

Let’s initialize the plugin and pass it as props.

import React, { Component } from "react";
import Editor, { createEditorStateWithText } from "@draft-js-plugins/editor";
import createEmojiPlugin from "@draft-js-plugins/emoji";
import editorStyles from "./editorStyles.module.css";

const emojiPlugin = createEmojiPlugin();
const { EmojiSuggestions, EmojiSelect } = emojiPlugin;
const plugins = [emojiPlugin];
const text = `Cool, we can have all sorts of Emojis here. ๐Ÿ™Œ
๐ŸŒฟโ˜ƒ๏ธ๐ŸŽ‰๐Ÿ™ˆ aaaand maybe a few more here ๐Ÿฒโ˜€๏ธ๐Ÿ—ป Quite fun!`;

export default class SimpleEmojiEditor extends Component {
  state = {
    editorState: createEditorStateWithText(text)
  };

  onChange = (editorState) => {
    this.setState({
      editorState
    });
  };

  focus = () => {
    this.editor.focus();
  };

  render() {
    return (
      <div>
        <div className={editorStyles.editor} onClick={this.focus}>
          <Editor
            editorState={this.state.editorState}
            onChange={this.onChange}
            plugins={plugins}
            ref={(element) => {
              this.editor = element;
            }}
          />
          <EmojiSuggestions />
        </div>
        <div className={editorStyles.options}>
          <EmojiSelect />
        </div>
      </div>
    );
  }
}

The EmojiSuggestion component will populate a list emojis for us and EmojiSelect will bring the selected Emoji.

Remember you need to add the CSS

import "@draft-js-plugins/mention/lib/plugin.css";

See the Live project in action on Sandbox

How to add mentions to Draft-js in React

How to add mentions to draft-js editor using plugin in React


Draft-js is Javascript Editor framework that featured in Facebook and it is an open source project which maintained by Facebook. It has larger user base compared to other. Draft-js was a complete framework for creating Ritch text editors and social interactions.

Plugin

Draft-js Plugins allow us to quickly add features such as tool bars , social mentions.

It is a React Plugin Architecture for Draft.js

Mention Plugin

The mention plugin allow us add mention feature in our editor, one like seen on Facebook, twitter etc. In real world we can fetch mentions from API, in this example we used JS object to store them.

Let’s install create a react project

npx create-react-app dracft-editor 

In the project add dependecies as follows

npm install @draft-js-plugins/editor
npm install @draft-js-plugins/mention draft-js

We are ready to build our component. Using the Editor component we can use Editor in our app. The Editor state will manage the state of the app.

Let’s initialize the plugin and pass it as props.

//SimpleMention.tsx
import React, {
  ReactElement,
  useCallback,
  useMemo,
  useRef,
  useState
} from "react";
import { EditorState } from "draft-js";
import Editor from "@draft-js-plugins/editor";
import createMentionPlugin, {
  defaultSuggestionsFilter
} from "@draft-js-plugins/mention";
import editorStyles from "./SimpleMentionEditor.module.css";

import mentions from "./Mentions";

export default function SimpleMentionEditor(): ReactElement {
  const ref = useRef<Editor>(null);
  const [editorState, setEditorState] = useState(() =>
    EditorState.createEmpty()
  );
  const [open, setOpen] = useState(false);
  const [suggestions, setSuggestions] = useState(mentions);

  const { MentionSuggestions, plugins } = useMemo(() => {
    const mentionPlugin = createMentionPlugin();
    // eslint-disable-next-line no-shadow
    const { MentionSuggestions } = mentionPlugin;
    // eslint-disable-next-line no-shadow
    const plugins = [mentionPlugin];
    return { plugins, MentionSuggestions };
  }, []);

  const onOpenChange = useCallback((_open: boolean) => {
    setOpen(_open);
  }, []);
  const onSearchChange = useCallback(({ value }: { value: string }) => {
    setSuggestions(defaultSuggestionsFilter(value, mentions));
  }, []);

  return (
    <div
      className={editorStyles.editor}
      onClick={() => {
        ref.current!.focus();
      }}
    >
      <Editor
        editorKey={"editor"}
        editorState={editorState}
        onChange={setEditorState}
        plugins={plugins}
        ref={ref}
      />
      <MentionSuggestions
        open={open}
        onOpenChange={onOpenChange}
        suggestions={suggestions}
        onSearchChange={onSearchChange}
        onAddMention={() => {
          // get the mention object selected
        }}
      />
    </div>
  );
}

Remember you need to add the CSS

import "@draft-js-plugins/mention/lib/plugin.css";

The complete project can be found on Sandbox

Create RichText editor in 5 minute using react-draft-wysiwyg

How to create a WYSIWYG text editor using draft-js in 5 minutes


Draft-js is Javascript Editor framework that featured in Facebook and it is an open source project which maintained by Facebook. It has larger user base compared to other. Draft-js was a complete framework for creating Ritch text editors and social interactions.

How to build a RichText Editor

It is primarily built for serving React, all you have to do get the dependencies and setup a project. Let’s setup a project.

npx create-react-app dracft-editor 

react-draft-wysiwyg

This is a React library which ready use component with preconfigured toolbars and other features on top of Draft-js and allow us to build text editor with ease and peace. Let’s add the dependencies.

$ npm install --save react-draft-wysiwyg draft-js

We are ready to build our component.

We can wither use or functional component for creating the Draftjs Editor. Add the following code in Editor.js file.

import { Editor } from "react-draft-wysiwyg";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
<Editor
  editorState={editorState}
  toolbarClassName="toolbarClassName"
  wrapperClassName="wrapperClassName"
  editorClassName="editorClassName"
  onEditorStateChange={this.onEditorStateChange}
/>;

See the Sandbox for Live example.

How to add inline toolbar plugin to Draft-js in React

How to add inline toolbar to draft-js editor using plugin in React


Draft-js is Javascript Editor framework that featured in Facebook and it is an open source project which maintained by Facebook. It has larger user base compared to other. Draft-js was a complete framework for creating Ritch text editors and social interactions.

Plugin

Draft-js Plugins allow us to quickly add features such as tool bars , social mentions.

It is a React Plugin Architecture for Draft.js

Inline Toolbar

The inline toolbar incorporate a toolbar for our editor, without the plugin we have to add all background details start from buttons, styles and function handler manually. This plugin will save our time.

Let’s install create a react project

npx create-react-app dracft-editor 

In the project add dependecies as follows

npm install @draft-js-plugins/editor
npm install @draft-js-plugins/inline-toolbar

We are ready to build our component. Using the Editor component we can use Editor in our app. The Editor state will manage the state of the app.

Let’s initialize the plugin and pass it as props.

import Editor from '@draft-js-plugins/editor';
import createToolbarPlugin from '@draft-js-plugins/static-toolbar';
import React from 'react';

// Creates an Instance. At this step, a configuration object can be passed in
// as an argument.
const toolbarPlugin = createToolbarPlugin();

// The Editor accepts an array of plugins. In this case, only the toolbarPlugin
// is passed in, although it is possible to pass in multiple plugins.
const MyEditor = ({ editorState, onChange }) => (
  <Editor
    editorState={editorState}
    onChange={onChange}
    plugins={[toolbarPlugin]}
  />
);

export default MyEditor;

The complete project can be found on Sandbox

How to use toolbar plugin with Draft-js in React

How to add astatic toolbar to draft-js editor using plugin in React


Draft-js is Javascript Editor framework that featured in Facebook and it is an open source project which maintained by Facebook. It has larger user base compared to other. Draft-js was a complete framework for creating Ritch text editors and social interactions.

Plugin

Draft-js Plugins allow us to quickly add features such as tool bars , social mentions.

It is a React Plugin Architecture for Draft.js

Static Toolbar

The static tool bar incorporate a toolbar for our editor, without the plugin we have to add all background details start from buttons, styles and function handler manually. This plugin will save our time.

Let’s install create a react project

npx create-react-app dracft-editor 

In the project add dependecies as follows

npm install @draft-js-plugins/editor
npm install @draft-js-plugins/static-toolbar

We are ready to build our component. Using the Editor component we can use Editor in our app. The Editor state will manage the state of the app.

Let’s initialize the plugin and pass it as props.

import Editor from '@draft-js-plugins/editor';
import createToolbarPlugin from '@draft-js-plugins/static-toolbar';
import React from 'react';

// Creates an Instance. At this step, a configuration object can be passed in
// as an argument.
const toolbarPlugin = createToolbarPlugin();

// The Editor accepts an array of plugins. In this case, only the toolbarPlugin
// is passed in, although it is possible to pass in multiple plugins.
const MyEditor = ({ editorState, onChange }) => (
  <Editor
    editorState={editorState}
    onChange={onChange}
    plugins={[toolbarPlugin]}
  />
);

export default MyEditor;

The complete project can be found on Sandbox

How to use draft-js with react

How to use Draft-js with React components


Draft-js is Javascript Editor framework that featured in Facebook and it is an open source project which maintained by Facebook. It has larger user base compared to other. Draft-js was a complete framework for creating Ritch text editors and social interactions.

How to use it in React

It is primarily built for serving React, all you have to do get the dependencies and setup a project.

npx create-react-app dracft-editor 

In the project add dependecies as follows

yarn add draft-js"

We are ready to build our component. Using the Editor component we can use Editor in our app. The Editor state will manage the state of the app.

We can wither use or functional component for creating the Draftjs Editor. Add the following code in Editor.js file.

import React, { useState } from "react";
import { Editor, EditorState, RichUtils } from "draft-js";
import { convertToRaw } from "draft-js";

const DraftJsEditor = () => {
  const [editorState, setEditorState] = useState(EditorState.createEmpty());

  const logContent = () => {
    const blocks = convertToRaw(editorState.getCurrentContent()).blocks;
    const value = blocks
      .map((block) => (!block.text.trim() && "\n") || block.text)
      .join("\n");
    console.log(value);
  };

  const handleKeyCommand = (command) => {
    const newState = RichUtils.handleKeyCommand(editorState, command);
    if (newState) {
      setEditorState(newState);
      return "handled";
    }
    return "not-handled";
  };

  const onUnderlineClick = () => {
    setEditorState(RichUtils.toggleInlineStyle(editorState, "UNDERLINE"));
  };

  const onBoldClick = () => {
    setEditorState(RichUtils.toggleInlineStyle(editorState, "BOLD"));
  };

  const onItalicClick = () => {
    setEditorState(RichUtils.toggleInlineStyle(editorState, "ITALIC"));
  };

  // We could make a toolbar component her to handle the formating tools
  // and replase the buttons with that.
  return (
    <div>
      <button onClick={onUnderlineClick}>U</button>
      <button onClick={onBoldClick}>
        <b>B</b>
      </button>
      <button onClick={onItalicClick}>
        <em>I</em>
      </button>
      <div className="editors">
        <Editor
          editorState={editorState}
          handleKeyCommand={handleKeyCommand}
          onChange={setEditorState}
        />
      </div>
      <div>
        <button onClick={logContent}>Log</button>
      </div>
    </div>
  );
};

export default DraftJsEditor;

The complete project can be found along with other examples on Github. See the Sandbox for Live example.

Add background image to div in Reactjs

How to change background of a div using inline css in Reactjs


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Background

In CSS we use background:url() for adding awesome background to a div tag. How bout Reactjs style ?

We can try the inline style

style={{background:url(props.background )

This don’t work, instead throw an error. Then what we do ? Let’s, turn the ‘url and brackets ‘ into string.

style={{background:'url('+props.background +')'

and it will work as expected

How to setup Formik in Reactjs

How to setup Formik for React forms


Formik is one of most popular React libraries, for managing forms and validations. It has inbuilt state-management system. The Fomik series of posts will cover all essential topics regarding form management using Formik.

Setup

As the very step we need to install the package and prepare our form. In this example we are using a simple login form.

yarn add formik
<form    >		
<input  type="email" placeholder="Email" name="email"  />
<input   type="password" placeholder="Password" name="password" />		 
<button   type='submit'>Sign In</button>
</form>

Formik hook

There are two ways to integrate formik with form, useFormik hook or use Formik component. We go with hook.

let’s configure the hook.

import { useFormik, Formik } from 'formik'
import * as Yup from 'yup'

const validationSchema = Yup.object({
		email: Yup.string().email('Invalid email format').required('Required'),
		password: Yup.string().required('Required'),
	});	
const formikLogin = useFormik({
		initialValues: {
			email: '',
			password: '',
		},
		onSubmit: async values => {
			  console.log(values);		 
		},
		validationSchema 
	});

For the form formik will handle a couple of things, onSubmit, onChange, validation, error generation etc.

All we have to fill few formik values and functions call.

<form   onSubmit={formikLogin.handleSubmit} >		
<input  type="email" placeholder="Email" name="email" value={formikLogin.values.email} onChange={formikLogin.handleChange}  />
{formikLogin.errors.email ? <div>{formikLogin.errors.email}</div> : null}
<input   type="password" placeholder="Password" name="password" value={formikLogin.values.password} onChange={formikLogin.handleChange}   />
{formikLogin.errors.password ? <div>{formik.errors.password}</div> : null}					 
<button   type='submit'>Sign In</button>
</form>

Note that form field’s name and formik field should be same.

Toggling state in Reactjs

How to toggle state in reactjs.


Reactjs is a frontend UI library for developing sophisticated web/native applications using Typescript/Javascript. The library is backed by Facebook and opensource community. For me it is like having a swiss knife in my tool kit.

Toggling a state

Toggling state can be necessary when switching buttons to a theme switcher. This can be done using the Javascript expression with the NOT(!) operator.

toggle: () => {
           darkTheme = true;
            darkTheme = !darkTheme;
        }

Here the darkTheme has true value and it can be invert to false using =! .

This is not a react feature, it is a plain Javascript operation.