In this tutorial, we will use the react-popup package which is a simple and Powerful react component. It's simple just add dependency import Popup from "reactjs-popup";which you can add to your project by following commandnpm add reactjs-popup --save |
Because reactjs-popup provides a child as function pattern, you have full control on Popup state |
Full code example given below: |
import React, { Component } from "react"; import "./styles.css"; import Popup from "reactjs-popup"; class App extends Component { constructor() { super(); this.state = { open: false }; this.openModal = this.openModal.bind(this); this.closeModal = this.closeModal.bind(this); this.popupOnClose = this.popupOnClose.bind(this); } openModal() { this.setState({ open: true }); } closeModal() { this.setState({ open: false }); } popupOnClose() {} render() { return ( <div> <span onClick={this.openModal}>Click here to open Popup</span> <Popup open={this.state.open} className="popup-modal-container-box" modal onOpen={e => this.popupOnClose(e)} onClose={this.popupOnClose} lockScroll={true} closeOnDocumentClick={false} > <h1>HELLO POPUP</h1> <span onClick={this.closeModal}>CLOSE</span> </Popup> </div> ); } } export default App; |
Full example is created on CodeSandbox.IO https://codesandbox.io/s/reactjs-create-react-modal-open-popup-using-reactjs-popup-dependency-qthyq |
Showing posts with label reactjs. Show all posts
Showing posts with label reactjs. Show all posts
Saturday, February 1, 2020
ReactJS Create React Modal Open Popup Using reactjs-popup Dependency
Friday, January 31, 2020
ReactJS - You tried to redirect to the same route you're currently on
It's a common problem when you redirect on same route will give a warning like You tried to redirect to the same route you're currently on: /profile/2. It's because of when we define Route we can not define for every parameters like 1, 2, 3 etc. Normally we define our Route like: <Route path="/profile/:id" component={Profile} /> And this will handle every URL like http://example.com/profile/1, http://example.com/profile/2 etc. |
But sometimes when we use Redirect component to redirect to another profile page from current profile page using the below code return <Redirect to={"/profile/" + this.state.id} push={true} />; The above warning thrown because our Route is same for all URL like /profile/1 as well as /profile/2. |
To avoid this warning we need to define key to our Route like below <Route path="/profile/:id" render={props => { return <Profile {...props} key={props.match.params.id} />; }} /> |
Full example is created on CodeSandbox.IO https://codesandbox.io/s/you-tried-to-redirect-to-the-same-route-youre-currently-on-063ot |
Thursday, January 2, 2020
Using Google Place Autocomplete API in React
I want to have an auto completing location search bar in my react component |
Reference Google Maps API JS library via /public/index.html file: |
Get google API Key from here -> https://developers.google.com/places/web-service/get-api-key
https://cloud.google.com/console/google/maps-apis/overview |
You need to enable Maps JavaScript API & Places Api from below links -> https://console.developers.google.com/google/maps-apis/apis/maps-backend.googleapis.com https://console.developers.google.com/google/maps-apis/apis/places-backend.googleapis.com |
import React from "react"; class MyComponent extends React.Component { constructor(props) { super(props); this.autocompleteInput = React.createRef(); this.autocomplete = null; this.handlePlaceChanged = this.handlePlaceChanged.bind(this); } componentDidMount() { this.autocomplete = new google.maps.places.Autocomplete( this.autocompleteInput.current, {"types": ["geocode"]} ); this.autocomplete.addListener('place_changed', this.handlePlaceChanged); } handlePlaceChanged(){ const place = this.autocomplete.getPlace(); this.props.onPlaceLoaded(place); } render() { return ( <input ref={this.autocompleteInput} id="autocomplete" placeholder="Enter your address" type="text"></input> ); } } export default MyComponent |
Wednesday, January 1, 2020
bootstrap-datepicker with React: onChange doesn't fire while onClick does
bootstrap-datepicker with React: onChange doesn't fire while onClick does |
import React, { Component } from 'react' import {Redirect} from "react-router-dom"; class MyComponent extends Component { constructor () { super(); this.state = { back: false, dateOfBirth: "", dateOfBirthInput: "" }; this.handleUserInput = this.handleUserInput.bind(this); } componentDidMount () { super.componentDidMount(); $(this.state.dateOfBirthInput).datepicker({ format: "mm/dd/yyyy" }); $(this.state.dateOfBirthInput).on('changeDate', function(e) { console.log(e); console.log(e.target.value); this.handleUserInput(e); }) } handleUserInput (e) { let name = e.target.name; let value = e.target.value; console.log(`Name=${name}, value=${value}`); this.setState({[name]: value}); } render () { if (this.state.back) { return <Redirect to={'/dashboard/user-profile'} push={true}/> } return ( <div> <div className="form-group row"> <label className={'col-12 col-sm-12 col-md-4 col-lg-3 col-xl-2 col-form-label'}>Date of birth</label> <div className="col-12 col-sm-12 col-md-8 col-lg-9 col-xl-10"> <div className='input-group date'> <input name={'dateOfBirth'} value={this.state.dateOfBirth} onChange={(e) => this.handleUserInput(e)} ref={(n) => this.state.dateOfBirthInput = n} type='text' className="form-control"/> </div> </div> </div> </div> ) } } export default MyComponent |
Saturday, December 28, 2019
Implementing Programically Redirect With React Router | React redirect to component | Redirect with React Router
A lot of these short blog posts are just for me to find later when I forget how to do something. |
So, there is an span where there is a click event named goToAnotherPage, when clicked I just set state the edit variable true, and it redirect to another page using react component named Redirect as described in function goToAnotherPage. |
import React, { Component } from 'react' import {Redirect} from 'react-router-dom' class SomePage extends Component { constructor () { super(); this.state = { edit: false }; this.goToAnotherPage = this.goToAnotherPage.bind(this); } componentDidMount () { super.componentDidMount(); } goToAnotherPage(e) { this.setState({'edit': true}); } render () { if (this.state.edit) { return <Redirect to={'/go-to-another-page'} push={true}/> } return ( <span onClick={(e) => this.goToAnotherPage(e)}>Go to another page</span> ) } } export default SomePage |
Thursday, December 19, 2019
ReactJS - Multiple Layout In React Using React Router | Using multiple layouts for react-router components
React Router is a standard routing library for React. |
In the first step, we will create two different layout files (named CommonLayout and DashboardLayout) and their respective routes to implement multiple layouts in React. |
CommonLayoutimport React, { Component } from 'react'; import {Route} from 'react-router-dom'; class CommonLayoutComponent extends React.Component{ constructor(props){ super(props); this.createRef = this.createRef.bind(this); } createRef(element) { console.log(element); } render() { return ( <div key="dashboard"> <div className="Content" ref={this.createRef}> {this.props.children} </div> </div> ); } } const CommonLayoutRoute = ({component: Component, ...rest}) => { return ( <Route {...rest} render={matchProps => ( <CommonLayoutComponent {...matchProps}> <Component {...matchProps} /> </CommonLayoutComponent> )} /> ) }; export default CommonLayoutRoute; |
DashboardLayoutimport React, { Component } from 'react'; import { Route } from 'react-router-dom'; const DashboardLayoutRoute = ({component: Component, ...rest}) => { return ( <Route {...rest} render={matchProps => ( <div> <h3>Dashboard Layout</h3> <Component {...matchProps} /> </div> )} /> ) }; export default DashboardLayoutRoute; |
Now, update your App.js file to use both - the layout and the component - as below. |
import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Redirect, Switch } from 'react-router-dom'; /** Layouts **/ import CommonLayoutRoute from "./CommonLayoutRoute"; import DashboardLayoutRoute from "./DashboardLayout"; /** Components **/ import LayoutPage1 from './LayoutPage1'; import LayoutPage2 from './LayoutPage2' /* App */ class App extends Component { render() { return ( <Router> <Switch> <Route exact path="/"> <Redirect to="/layout1" /> </Route> <CommonLayoutRoute path="/layout1" component={LayoutPage1} /> <DashboardRoute path="/layout2" component={LayoutPage2} /> </Switch> </Router> ); } } export default App; |
Here, we have updated the App.js file as defined in the route. When we route to /layout1, then CommonLayoutRoute (our first layout) will be used as the master page for the component LayoutPage1. On the other hand, when we route to /layout2, then our second layout, i.e., DashbaordLayoutRoute will be used as the master page for the component LayoutPage2. |
Wednesday, December 18, 2019
ReactJS - Preventing Form Submission
I've been experimenting with React. In my experiement, I'm using the React framework. When I click a button, I've noticed that the HTML form submits. Is there a way to prevent form submission when a button is clicked? Just need to add the following attribute to the form. |
<form onSubmit={(e) => e.preventDefault()}> </form> |
Monday, December 2, 2019
How to access a DOM element in React? What is the equilvalent of document.getElementById() in React | ReactJS access HTML Element Node Reference
React supports a good way to set refs called “callback refs”, which gives more fine-grain control over when refs are set and unset. |
Instead of passing a ref attribute created by createRef(), you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. |
The example below implements a common pattern: using the ref callback to store a reference to a DOM node in an instance property. |
class CustomTextInput extends React.Component { constructor(props) { super(props); this.textInput = null; this.setTextInputRef = element => { this.textInput = element; }; this.focusTextInput = () => { // Focus the text input using the raw DOM API if (this.textInput) this.textInput.focus(); }; } componentDidMount() { // autofocus the input on mount this.focusTextInput(); } render() { // Use the `ref` callback to store a reference to the text input DOM // element in an instance field (for example, this.textInput). return ( <div> <input type="text" ref={this.setTextInputRef} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } } |
Sunday, November 24, 2019
ReactJS Render HTML string as real HTML in a React component
First need to install react-html-parser to render html as html element in react js. |
Run below command to add the dependency:
npm add react-html-parser |
Then use as below: import ReactHtmlParser from 'react-html-parser'; |
import axios from 'axios' import React, { Component } from 'react' import { Link } from 'react-router-dom' import MainActivity from "./MainActivity"; import ReactHtmlParser from 'react-html-parser'; class ProjectsList extends MainActivity { constructor () { super(); this.state = { projects: [], loading: true, html: "" }; } componentDidMount () { axios.get(`${this.APP_URL}/api/projects`).then( response => { console.log(response); this.setState({ projects: response.data, loading: false, html: response.data.html }) }) } render () { if (this.state.loading) { return this.loader() } if (this.state.html) { return <div>{ ReactHtmlParser(this.state.html) }</div>; } const { projects } = this.state; return ( <div className='container py-4'> <div className='row justify-content-center'> <div className='col-md-8'> <div className='card'> <div className='card-header'>All Projects</div> <div className='card-body'> <Link className='btn btn-primary btn-sm mb-3' to='/project/create'> + Create New Project </Link> <ul className='list-group list-group-flush'> {projects.map(project => ( <Link className='list-group-item list-group-item-action d-flex justify-content-between align-items-center' to={`/project/${project.id}`} key={project.id}> {project.name} <span className='badge badge-primary badge-pill'>{project.tasks_count}</span> </Link> ))} </ul> </div> </div> </div> </div> </div> ) } } export default ProjectsList |
Subscribe to:
Posts (Atom)