Posts

Showing posts with the label Reactjs

Console Logging For React?

Image
Answer : If you're just after console logging here's what I'd do: export default class App extends Component { componentDidMount() { console.log('I was triggered during componentDidMount') } render() { console.log('I was triggered during render') return ( <div> I am the App component </div> ) } } Shouldn't be any need for those packages just to do console logging. Here are some more console logging "pro tips": console.table var animals = [ { animal: 'Horse', name: 'Henry', age: 43 }, { animal: 'Dog', name: 'Fred', age: 13 }, { animal: 'Cat', name: 'Frodo', age: 18 } ]; console.table(animals); console.trace Shows you the call stack for leading up to the console. You can even customise your consoles to make them stand out console.todo = function(msg) { console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘...

Cancel All Subscriptions And Asyncs In The ComponentWillUnmount Method, How?

Answer : You can use isMounted React pattern to avoid memory leaks here. In your constructor: constructor(props) { super(props); this._isMounted = false; // rest of your code } componentDidMount() { this._isMounted = true; this._isMounted && this.getImage(this.props.item.image); } in your componentWillUnmount componentWillUnmount() { this._isMounted = false; } While in you getImage() async getImage(img) { let imgUri = await Amplify.Storage.get(img) let uri = await CacheManager.get(imgUri).getPath() this._isMounted && this.setState({ image: { uri }, ready: true }) } A recommend approach to use Axios which is based cancellable promise pattern. So you can cancel any network call while unmounting the component with it's cancelToken subscription . Here is resource for Axios Cancellation From the React blog Just set a _isMounted property to true in componentDidMount and set it to false in ...

Can't Get The Target Attributes Of Material-ui Select React Component

Answer : Update 2 In response to your comments: As per the material-ui docs, getting back the touchtap event on option element rather than the select element is expected. If you want the id and name of the element, I would suggest binding the variables to the callback: The onchange method in the parent component: _onChange(id, name, evt, key, payload) { console.log(id); //id of select console.log(name); //name of name console.log(payload); //value of selected option } And when you attach it to the select component, you need to use bind <Select value={this.props.test} name={"test"} id={"test"} onChange={this.props.onChange.bind(null,"id","name")} hintText={"Select a fitch rating service"}> Update Here are the react event docs. Under the event-pooling you will find reference to the use of e.persists() in the block quote. The explanation given in this issue is that React pools t...

Can't Perform A React State Update On An Unmounted Component

Answer : Here is a React Hooks specific solution for Error Warning: Can't perform a React state update on an unmounted component. Solution You can declare let isMounted = true inside useEffect , which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally: useEffect(() => { let isMounted = true; // note this flag denote mount status someAsyncOperation().then(data => { if (isMounted) setState(data); }) return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted }); const Parent = () => { const [mounted, setMounted] = useState(true); return ( <div> Parent: <button onClick={() => setMounted(!mounted)}> {mounted ? "Unmount" : "Mount"} Child </button> {mounted && <Child />} <p> Unmount Child, while it is still ...

Call Function OnPress React Native

Answer : In you're render you're setting up the handler incorrectly, give this a try; <View> <Icon name='heart' color={this.state.myColor} size= {45} style={{marginLeft:40}} onPress={this.handleClick} /> </View> The syntax you're using would make sense for declaring an anonymous function inline or something but since your handler is defined on the class, you just reference it (not call it) using this.functionName in the props. A little late to the party, but just wanted to leave this here if someone needs it export default class mainScreen extends Component { handleClick = () => { //some code } render() { return( <View> <Button name='someButton' onPress={() => { this.handleClick(); //usual call like vanilla javascript, but uses this operator }} ...

Can't Create WebStorm React Project

Answer : You need to install create-react-app npm module, before you use this feature. npm install -g create-react-app You can read more about this feature on the official release blog of WebStorm. Excerpt from the documentation : Make sure that you have create-react-app installed globally on your computer, for that run npm install -g create-react-app. Then to start your new project, double click on the start task in the npm tasks tool window to run it. That’s it! I had ie installed create-react-app globally using yarn and webstorm failed to find it. Then I used npm , not to mention globally and its working like a charm.

Add A Class To The HTML Tag With React?

Answer : TL;DR use document.body.classList.add and document.body.classList.remove I would have two functions that toggle a piece of state to show/hide the modal within your outer component. Inside these functions I would use the document.body.classList.add and document.body.classList.remove methods to manipulate the body class dependant on the modal's state like below: openModal = (event) => { document.body.classList.add('modal-open'); this.setState({ showModal: true }); } hideModal = (event) => { document.body.classList.remove('modal-open'); this.setState({ showModal: false }); } With the new React (16.8) this can be solved with hooks: import {useEffect} from 'react'; const addBodyClass = className => document.body.classList.add(className); const removeBodyClass = className => document.body.classList.remove(className); export default function useBodyClass(className) { useEffect( () => { // Se...

Accessing Previous Theme Variables In CreateMuiTheme

Answer : You'd need to create an instance of the default theme and use it when defining your own: import { createMuiTheme } from 'material-ui/styles'; const defaultTheme = createMuiTheme(); const theme = createMuiTheme({ typography: { fontSize: defaultTheme.typography.fontSize + 2 } }); export default theme; You can also create your theme and then add on to it after theme is created. import { createMuiTheme } from 'material-ui/styles'; const theme = createMuiTheme(); theme.typography = { ...theme.typography, fontSize: theme.typography.fontSize + 2 } export default theme;

Can I Use React Bootstrap With Next.js?

Answer : It is obviously possible to use react-bootstrap in a nextjs application. The only problem you might encounter will be in the rendering of your application if javascript is disabled in user's browser if you use react-bootstrap components to build your layout (see example below). Nextjs allows you to display SSG/SSR pages, javascript-disabled users will see your app but the layout will be messy. But if you still want to go with it: npm i react-bootstrap bootstrap Import bootstrap styles in your _app.js: import 'bootstrap/dist/css/bootstrap.min.css'; You can then use your react-bootstrap components as you would do in reactjs: import {Container, Row, Col} from 'react-bootstrap'; const Layout = () => ( <> <Container fluid> <Row> <Col> <p>Yay, it's fluid!</p> </Col> </Row> </Container> </> ); export default Layout; Yes...

Add A React-bootstrap Alert To HandleSubmit In Formik

Answer : Use state and conditional rendering. Instead of returning a component set state to a variable, in your render use conditional rendering to check if the value is true. handleSubmit = (formState, { resetForm }) => { // Now, you're getting form state here! const payload = { ...formState, role: formState.role.value, createdAt: firebase.firestore.FieldValue.serverTimestamp() }; console.log('formvalues', payload); fsDB .collection('register') .add(payload) .then(docRef => { resetForm(initialValues); }) .then(e => this.setState({ alert: true })) .catch(error => { console.error('Error adding document: ', error); }); }; In your render render() { ... return( .... {this.state.alert && <AlertDismissible />} ... ) } Example Demo Complete form import React from 'react'; import { Link } from 'react-router-dom'; import { Formik, Form, F...

ComponentWillReceiveProps Has Been Renamed

Answer : It seems this has been reported to the maintainers already. Now, as a consumer of an open source software, you may: wait for them to fix (or not fix) the problem be cool and submit a PR to fix it for them :) Here are all the references to componentWillReceiveProps in the repo find a new package to use Ultimately, this isn't an error related to your software, but the dependencies it relies on. It isn't really your responsibility to fix those. If your app runs, it'll be fine. Warnings from react-dom.development.js won't appear in production. Use getDerivedStateFromProps instead of componentWillReceiveProps For example: Before: // Before class ExampleComponent extends React.Component { state = { isScrollingDown: false, }; componentWillReceiveProps(nextProps) { if (this.props.currentRow !== nextProps.currentRow) { this.setState({ isScrollingDown: nextProps.currentRow > this.props.currentRow, }); } } } After...

Can You Use Es6 Import Alias Syntax For React Components?

Answer : Your syntax is valid. JSX is syntax sugar for React.createElement(type) so as long as type is a valid React type, it can be used in JSX "tags". If Button is null, your import is not correct. Maybe Button is a default export from component-library. Try: import {default as StyledButton} from "component-library"; The other possibility is your library is using commonjs exports i.e. module.exports = foo . In this case you can import like this: import * as componentLibrary from "component-library"; Update Since this is a popular answer, here a few more tidbits: export default Button -> import Button from './button' const Button = require('./button').default export const Button -> import { Button } from './button' const { Button } = require('./button') export { Button } ...

Can Redux Be Seen As A Pub/sub Or Observer Pattern?

Answer : Redux is not supposed to "replace the initial idea of react.js", think of it more like a library to managed shared state between components and to coordinate state mutations. Redux does use a pub/sub pattern indeed, see the store methods here: http://redux.js.org/docs/api/Store.html#store-methods You'll find a subscribe method that is used by components to subscribe to changes in the state tree. Normally you don't use store.subscribe directly, as the Redux-React bindings (Redux connect basically) do that for you. You can check out the actual implementation here, it's not that complicated to follow (in fact to me that's the main benefit of Redux over other Flux implementations): https://github.com/reduxjs/react-redux/blob/4.x/src/components/connect.js#L199 That code, apart from subscribing to the changes emitted by the store, also perform some optimisations, such as passing new props to the component (and hence triggering a re-render) only when ...

Correct Path For Img On React.js

Answer : In create-react-app relative paths for images don't seem to work. Instead, you can import an image: import logo from './logo.png' // relative path to image class Nav extends Component { render() { return ( <img src={logo} alt={"logo"}/> ) } } If you used create-react-app to create your project then your public folder is accessible. So you need to add your image folder inside the public folder. public/images/ <img src="/images/logo.png" /> You're using a relative url, which is relative to the current url, not the file system. You could resolve this by using absolute urls <img src ="http://localhost:3000/details/img/myImage.png" /> But that's not great for when you deploy to www.my-domain.bike, or any other site. Better would be to use a url relative to the root directory of the site <img src="/details/img/myImage.png" />

Adding Border Only To The One Side Of The Component In React Native (iOS)

Answer : Even though borderBottom doesn't work on the Text component, it did work for me on the TextInput component, just set editable to false and set the value to your desired text as so... <TextInput style={styles.textInput} editable={false} value={'My Text'}/> const styles = StyleSheet.create({ textInput: { borderBottomColor: 'black', borderBottomWidth: 1, } }); This isn't currently possible. See the following RN issue: https://github.com/facebook/react-native/issues/29 and this ticket on Product Pains: https://productpains.com/post/react-native/add-borderwidth-left-right-top-bottom-to-textinput-/

Conditionally Import Assets In Create-react-app

Answer : In the days when React didn't exist we didn't put assets into our JS files. We let the CSS to decide, what assets to load for what selectors. Then you could simply switch a corresponding class on or off for a corresponding element ( or even the whole page ) and viola it changes color, background, or even a form. Pure magic! Ah. What times these were! All above is true and I do not understand why would anyone do or recommend doing it differently. However if you still want to do it ( for any reason ) - you can! Latest create-react-app comes with out-of-the-box support for lazy loading of arbitrary components via dynamic importing and code splitting. All you need to do is use parenthesized version of the import() statement instead of the regular one. import() takes in a request string as usual and returns a Promise. That's it. Source code of the dynamicaly requested component won't be bundled in, but instead stored in separate chunks to be loaded on demand. ...

Can You Catch All Errors Of A React.js App With A Try/catch Block?

Answer : React 16 introduced Error Boundaries and the componentDidCatch lifecycle method: class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service logErrorToMyService(error, info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return <h1>Something went wrong.</h1>; } return this.props.children; } } Then you can use it as a regular component: <ErrorBoundary> <MyWidget /> </ErrorBoundary> Or you can wrap your root component with the npm package react-error-boundary, and set a fallback component and behavior. import {ErrorBoundary} from 'react-error-boundary'; const myErrorHandler = (error: Error, componentStack: string) => { //...

Can I Use React-select In React-native?

Answer : You can't use select2 or react-select with react-native, because it's DOM based and so, it will work only in navigator, not in react-native The closest react-native equivalent I've found is react-native-multiple-select, you can find it on github at https://github.com/toystars/react-native-multiple-select or install it with npm i react-native-multiple-select Probably the closest to what you want that comes bundled with React Native is http://facebook.github.io/react-native/docs/picker.html The Picker component will give you a tumbler thing on iOS and a dropdown on Android Alternatively maybe this 3rd party component is closer to what you want: https://github.com/bulenttastan/react-native-list-popover From How to use React native select box

Adding Marker To Google Maps In Google-map-react

Answer : Edit: Since this answer was posted the docs (and likely, the API) of the GoogleMapReact element was changed to support children. Any child with lat and lng would be rendered at the corresponding location on the map, as also indicated by @Jobsamuel's answer. The onGoogleApiLoaded callback should not be used for this purpose, as it is inferior to the declarative style and would not be re-run if changes are made to the map. Original answer (outdated): This may not be entirely clear from the description in the Readme, but the maps argument is, in fact, the maps API object (and map is, of course, the current Google Map instance). Therefore, you should pass both to your method: onGoogleApiLoaded={({map, maps}) => this.renderMarkers(map, maps)} and use them: renderMarkers(map, maps) { let marker = new maps.Marker({ position: myLatLng, map, title: 'Hello World!' }); } Adding a marker on your map isn't as easy as we would like to, mo...