Posts

Showing posts with the label reactjs

Creating React component vs using CSS styling

Creating React component vs using CSS styling I have created a tab menu using CSS styling that I use in several different spots in my ReactJS app. .tab { overflow: hidden; border: 1px solid #ccc; background-color: #f1f1f1; margin: 0; padding: 0; } .tab button { background-color: inherit; float: left; border: none; outline: none; cursor: pointer; padding: 14px 16px; transition: 0.3s; } .tab button:hover { background-color: #ddd; } .tab button:disabled { background-color: #ccc; cursor: default; } .tabcontent { display: none; padding: 6px 12px; border: 1px solid #ccc; border-top:none; } This is in a index.css file that sits with all my .js files. Within my React code I use it like this, as an example: index.css .js <table><tbody> <tr className="tab"><td> <button onClick={() => this.openTab(0)}>Tab 1</button> <button onClick={() => this.op...

global is not defined while using socket.io-client with webpack

global is not defined while using socket.io-client with webpack I am getting following error when i have added socket.io-client plugin in my React web app. socket.io-client Uncaught ReferenceError: global is not defined at Object../node_modules/socket.io-parser/is-buffer.js (is-buffer.js:4) at webpack_require (bootstrap:22) at Object../node_modules/socket.io-parser/binary.js (binary.js:8) at webpack_require (bootstrap:22) at Object../node_modules/socket.io-parser/index.js (index.js:8) at webpack_require (bootstrap:22) at Object../node_modules/socket.io-client/lib/index.js (index.js:7) at webpack_require (bootstrap:22) at Object../src/client/components/gettingStarted/socketest.js (socketest.js:1) at webpack_require (bootstrap:22) The following is my webpack config file. /*eslint-disable*/ var Path = require('path'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var FileChanger = require('webp...

No rounded corners on React-Bootstrap-NavItem

No rounded corners on React-Bootstrap-NavItem I want to have the same look as the pills style but without the rounded corners pills this is what i have so far <style type="text/css">{` .nav-pills > li + li { border-radius: 0 !important; } `}</style> <Nav bsStyle="pills" justified activeKey={this.props.currentStep} onSelect={this.updateCurrentStep.bind(this)} > <NavItem eventKey={1} title="Template">Template</NavItem> <NavItem eventKey={2} title="Edit">Edit</NavItem> <NavItem eventKey={3} title="Preview">Preview</NavItem> </Nav> How do I set the border-radius of my NavItem to 0? It does appear in the rules of the li item but it does not change anything. border-radius NavItem li 2 Answers 2 There are many different (and arguably better) ways to handle...

Getting the Height of Navigation bar dynamically in CSS

Getting the Height of Navigation bar dynamically in CSS My website is based on React and react-strap. Well, I had my .header-overlay to cover the whole entire background in .header . But what is happening here is that because of the .navbar , the .header-overlay sticks out of .header vertically. .header-overlay .header .navbar .header-overlay .header I figured that using calc(100vh - heightOfNavigationBar) would resolve this. But, I couldn't find any way to get the height of .navbar by dynamically. Is there any way to resolve this? (navbar is embedded in react-strap) calc(100vh - heightOfNavigationBar) .navbar CSS CODE: .navbar{ font-size: 20px; } .header { background: url("../images/headerbg.jpg") no-repeat 50% 50% fixed ; background-size: cover; -moz-background-size: cover; -o-background-size: cover; -webkit-background-size: cover; height: 100vh; } .header-overlay { background-color: rgba(31, 31, 31, 0.4); height: 100vh; } HTML C...

How to unit test a React component that renders after fetch has finished?

How to unit test a React component that renders after fetch has finished? I'm a Jest/React beginner. In jest's it I need to wait until all promises have executed before actually checking. it My code is similar to this: export class MyComponent extends Component { constructor(props) { super(props); this.state = { /* Some state */ }; } componentDidMount() { fetch(some_url) .then(response => response.json()) .then(json => this.setState(some_state); } render() { // Do some rendering based on the state } } When the component is mounted, render() runs twice: once after the constructor runs, and once after fetch() (in componentDidMount() ) finishes and the chained promises finish executing). render() fetch() componentDidMount() My testing code is similar to this: describe('MyComponent', () => { fetchMock.get('*', some_response); it('renders something', () => {...

Attach Authorization header for all axios requests

Attach Authorization header for all axios requests I have a react/redux application that fetches a token from an api server. After the user authenticates I'd like to make all axios requests have that token as an Authorization header without having to manually attach it to every request in the action. I'm fairly new to react/redux and am not sure on the best approach and am not finding any quality hits on google. Here is my redux setup: // actions.js import axios from 'axios'; export function loginUser(props) { const url = `https://api.mydomain.com/login/`; const { email, password } = props; const request = axios.post(url, { email, password }); return { type: LOGIN_USER, payload: request }; } export function fetchPages() { /* here is where I'd like the header to be attached automatically if the user has logged in */ const request = axios.get(PAGES_URL); return { type: FETCH_PAGES, payload: request }; } // reducers.js const initi...

Mapping / Looping inside dumb component in React

Mapping / Looping inside dumb component in React I create a dumb component that used by so many data, but same display. The problem is, is it better dumb component to accept only native data type or array of object? since my data property is difference each table. <ScrollView> {listOfData.map(()=>( <Dumb title={data.title} description={data.description} > ))} </ScrollView> pros: No object properties dependancy cons: Need Loop in smart component which make it messy vs <ScrollView> <Dumbs data={listOfData} > </ScrollView> pros: More simple in smart component cons: The dumb component only accept specific data properties So which one better? I do use a second one and mapping it in my component.ts first to change object properties, but it make component.ts messy 2 Answers 2 I think the nicest way would be: <ScrollView> {listOfData.map((data) =...

Convert HTML with JSP expression syntax into React component?

Convert HTML with JSP expression syntax <%= %> into React component? Inside my react project I am integrating a backend server API to make web application work. While working on the API's, I came across an API which returns the HTML page which has JSP expression syntax in it. My job is to convert that response into React Component so that it can be integrated into the web app. Check the below-given response I get from the API. <html> <head> <title>Food Payment Check-Out</title> </head> <body> <center> <h1>Please do not refresh this page...</h1> </center> <form method="post" action="https://pguat.paytm.com/oltp-web/processTransaction" name="paymentForm"> <input type="hidden" name='<%= REQUEST_TYPE %>' value='<%= DEFAULT %>'> <input type="hidden" na...

How to resolve warning with ESlint: Disallow Assignment in return Statement (no-return-assign)?

Image
How to resolve warning with ESlint: Disallow Assignment in return Statement (no-return-assign)? I'm using the following package in my React application to generate a Recaptcha component: https://github.com/appleboy/react-recaptcha Here is what the component looks like, with the eslint warning: this.recaptchaRef is defined like so: this.recaptchaRef = React.createRef(); this.recaptchaRef this.recaptchaRef = React.createRef(); This ref allows me to reset the Recaptcha when there is an error with my form like so: this.recaptchaRef.reset(); this.recaptchaRef.reset(); How would I be able to resolve this error without writing ESlint comments? 2 Answers 2 Arrow functions, if there is no { following the => , will return whatever expression follows. At the moment, your arrow function is assigning event to this.recaptchaRef and returning event . (even if the consumer completely ignores the return ...

test timers in react, sinon or jest

test timers in react, sinon or jest I have a funtion checkIdleTime , being set to be called periodically. checkIdleTime componentDidMount() { var idleCheck = setInterval(this.checkIdleTime.bind(this), authTimeoutSeconds * 1000); this.setState({idleCheck: idleCheck}); document.onkeypress = this.setActive; } I want to use the fake timer for test, but can't figure out how, tried sinon and jest . sinon jest beforeEach(() => { checkIdleTime = jest.spyOn(PureMain.prototype, 'checkIdleTime'); wrapper = shallow( <PureMain/> ); jest.useFakeTimers(); //clock = sinon.useFakeTimers(); }); it('should check the idle time after [authTimeoutSeconds] seconds of inactivity', () => { wrapper.instance().componentDidMount(); var idleCheck_timeout = wrapper.instance().state.idleCheck; expect(idleCheck_timeout).not.toEqual(null); expect(idleCheck_timeout._idleTimeout).toBe(authTimeoutSeconds * 1000); jest.runAllTi...

Sharing store change event between same hierarchical level child components

Sharing store change event between same hierarchical level child components I am developing a simple React JS application for learning purpose. I just started learning React JS a few days ago. Now, I am having a problem with Flux Store. I need to share the change event across two child components on the same hierarchical level. Please, see my scenario below. I have the parent component, called TodoComponent with the following definition //Create class TodoComponent extends React.Component{ constructor(props){ super(props) } render(){ return ( <div> <div> <ListComponent /> </div> <AddItemComponent /> </div> ) } } It has two child components called, ListComponent and the AddItemComponent. Moreover, I have a store with this definition. import { EventEmitter } from 'events'; class DataStore extends EventEmitter{ cons...

ReactJS API Data Fetching CORS error

ReactJS API Data Fetching CORS error I've been trying to create a react web app for a few days now for my internship and I've encountered a CORS error. I am using the latest version of reactJS, and placing this in the create-react-app , and below is the code for fetching: create-react-app componentDidMount() { fetch('--------------------------------------------',{ method: "GET", headers: { "access-control-allow-origin" : "*", "Content-type": "application/json; charset=UTF-8" }}) .then(results => results.json()) .then(info => { const results = info.data.map(x => { return { id: x.id, slug: x.slug, name: x.name, address_1: x.address_1, address_2: x.address_2, city: x.city, state: x.state, postal_code: x.postal_code, country_code: x.country_code, phone_number: x.phone_number, } }) th...

React, Firebase: Access values of JSON and also get key value

React, Firebase: Access values of JSON and also get key value I am beginner working with firebase, react. I am able to get the required data from firebase based on userEmail. But I am very confused in accessing the data. firebase.database().ref('/users').orderByChild('email').equalTo(userEmail).on('value', data => { console.log('data: ', data); }) I get the following output: data: Object { "-Lhdfgkjd6fn3AA-": Object { "email": "t5@gmail.com", "favQuote": "this is it", "firstName": "t5", "lastName": "l5", }, } Please help me how to access all values ("-Lhdfgkjd6fn3AA-" , firstname, lastname, email and favQuote) into variables like: data.firstName, data.lastName, data.key, etc . Thank you. You can get the value using: data.-Lhdfgkjd6fn3AA-.email – NullPoint...

Web Runtime alternatives to Electron/nw.js for Centos 6?

Web Runtime alternatives to Electron/nw.js for Centos 6? I know my title sounds crazy, as right now the popular practice is to use something like Electron or nw.js for desktop applications written using web stack technologies, but here's why I'm searching for alternative desktop web runtime solutions: So, to minimize code paths and maximize compatibility, my options appear to be: Has anyone else tried to bridge this gap to consolidate desktop apps and web apps when unfortunately Electron/nw.js aren't viable? Or does the simplification I'm searching for simply not exist? Can you run Electron in a Docker container on your Centos machine? That might be a possible cross-platform solution for you. Perhaps this would be helpful: stackoverflow.com/questions/39930223/… – Matt Morgan Jul 2 at 0:29 Thanks...