Posts

Showing posts with the label Reactjs

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-/

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 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...

Cannot Read Property 'history' Of Undefined (useHistory Hook Of React Router 5)

Answer : Its because the react-router context isn't set in that component. Since its the <Router> component that sets the context you could use useHistory in a sub-component, but not in that one. Note to other people that run into this problem and already have wrapped the component with Router component. Make sure that Router and the useHistory hook are imported from the same package. The same error can be thrown when one of them are imported from react-router and the other one from react-router-dom and the package versions of those packages don't match. Don't use both of them, read about the difference here. useHistory won't work in the component where you have your Routes because the context which is needed for useHistory is not yet set. useHistory will work on any child component or components which your have declared in your Router but it won't work on Router 's parent component or Router component itself.

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 ...

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 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 } ...

Axios Delete Request With Body And Headers?

Answer : So after a number of tries, I found it working. Please follow the order sequence it's very important else it won't work axios.delete(URL, { headers: { Authorization: authorizationToken }, data: { source: source } }); axios.delete does support a request body. It accepts two parameters: url and optional config. You can use config.data to set the request body and headers as follows: axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); See here - https://github.com/axios/axios/issues/897 Here is a brief summary of the formats required to send various http verbs with axios: GET : Two ways First method axios.get('/user?ID=12345') .then(function (response) { // Do something }) Second method axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { // Do something }) The two above are equivalent. Observe the params...

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 ...

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...

Bootstrap Dropdown Not Opening First Click On React 16

Answer : You may have jQuery or Bootstrap included twice. I don't use React, but I was having the same problem with Angular. It turns out that I was including jQuery/Bootstrap in my index.html as well my "scripts" configuration (which I think would be your "entry"). You should import this line and Test again : import 'bootstrap/dist/js/bootstrap.bundle'; this work for me like a charm :) I got the same issue. I noticed that when i was using bootstrap.min.js and jquery.min.js at a same time. Then my dropdown takes two click for toggle in first time after page load. Then i commented bootstrap.min.js . Now it is not giving me this issue. Try this. Maybe it will solve your problem.

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.

Cannot Resolve Module 'react-dom'

Answer : Issue is react-dom is not installed, when you hit npm -v react-dom , it gives you the version of npm not react-dom version, you can check that by using npm -v or npm -v react-dom both will give you the same result. You are checking the package version incorrectly. How to install react and react-dom properly? Use this to install react and react-dom: npm install react react-dom --save After that, you can check your package.json file, if react and react-dom has been installed correctly, you will find an entry for that. How to check install package version? To check all the locally installed packages version: npm list For globally installed packages, use -g also: npm list -g To check the version of any specific package, specify the package name also: npm list PackageName For Example => npm list react npm list react-router After installation your package.json will look like this: { "name": "***", ...

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...

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 ...

Attempted Import Error: 'addLocaleData' Is Not Exported From 'react-intl'

Answer : I'm still investigating but it looks like addLocaleData was removed as a breaking change for v3. https://formatjs.io/docs/react-intl/upgrade-guide-3x This was a bit confusing for me too because a lot of the tutorials and guides out there still use addLocaleData.

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...

Ant Design Responsive NavBar

Image
Answer : I was looking at this question in a decision to pick Ant design for a project. Responsive navbar is common scenario, but I was wondering why there is no such thing in Ant Design? Then I searched for issues in the repo and found the Ant Design Mobile as a comment to an issue. They have a separate package for mobile devices. Inside Ant Design Mobile there is separate section for web components. In that section you can find a Menu component which is suitable for mobile devices hamburger icon. Hope this will be helpful for future readers. I was looking for such functionality not long ago as well and in order to make Ant Menu responsive, I have written a simple React Component. This Component accepts Ant Menu markup as a prop and conditionally renders the Menu based on the viewport width, either as is (for desktop), or in a Popover component which will wrap passed menu markup (for mobile). I'm including screenshots of how it may look once the viewport is narrow en...

Cannot Scroll To Bottom Of ScrollView In React Native

Answer : Apply padding styles to "contentContainerStyle" prop instead of "style" prop of the ScrollView. I had just a ScrollView in my application and it was working fine. Then I added a header component at the top, and the bottom of my ScrollView was not visible any more. I tried everything and nothing worked. Until I found a solution after an hour of trying every crazy thing and here it is. I fixed the issue by adding paddingBottom as contentContainerStyle to my ScrollView . <ScrollView contentContainerStyle={{paddingBottom: 60}} > {this.renderItems()} </ScrollView> set flexGrow: 1 to contentContainerStyle of your ScrollView contentContainerStyle={{ flexGrow: 1 }}

Best Way To Polyfill ES6 Features In React App That Uses Create-react-app

Answer : Update : The create-react-app polyfill approach and docs have changed since this question/answer. You should now include react-app-polyfill (here) if you want to support older browsers like ie11. However, this only includes the " ...minimum requirements and commonly used language features ", so you'll still want to use one of the approaches below for less common ES6/7 features (like Array.includes ) These two approaches both work: 1. Manual imports from react-app-polyfill and core-js Install react-app-polyfill and core-js (3.0+): npm install react-app-polyfill core-js or yarn add react-app-polyfill core-js Create a file called (something like) polyfills.js and import it into your root index.js file. Then import the basic react-app polyfills, plus any specific required features, like so: /* polyfills.js */ import 'react-app-polyfill/ie11'; import 'core-js/features/array/find'; import 'core-js/features/array/includes'; ...