I am new to React and trying to add the Floating Menu Button from this Package.
Adding this I get following Error.
Parsing error: Unexpected token
I have uploaded the Code.
https://codesandbox.io/s/adding-floatingmenu-2tfxe?file=/src/App.js
I also have another Question. What is the difference of adding render() {} infront of return() or just leaving return()?
Update
I have Updated my Code inside codesandbox, there i do not receive an Error, after I copied it into VSCode i receive following error.
You can use react hooks only in functional components. If you use class components you not allowed to use hooks.
But what is a Hook?
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes.
Second question the same situation, render() uses in class components, in functional components you just use return(<></>)
Please read hooks owerview:
https://reactjs.org/docs/hooks-overview.html
If you want to initialize the isOpen state as false, here's a minimal example of that
import React, { Component } from "react";
import {
FloatingMenu,
MainButton,
ChildButton,
} from "react-floating-button-menu";
export default class Login extends Component {
constructor(props) {
super(props)
this.state = {
isOpen: false
}
}
render() {
return (
<FloatingMenu
slideSpeed={500}
direction="up"
spacing={8}
isOpen={this.state.isOpen}
>
<MainButton
backgroundColor="black"
onClick={() => this.setState({ open: !this.state.isOpen })}
size={56}
/>
</FloatingMenu>
);
}
};
Make sure you import Component from 'react' at the top. Render method is required when you're making a React component using a class method which you are using. It's a type of lifecycle method which is invoked when the component needs to update. The return statement only returns the data/JSX elements wherever it is being used.
If you are using functional components, you don't need a render method since they return the react elements themselves
Related
This question already has answers here:
componentDidMount equivalent on a React function/Hooks component?
(11 answers)
Closed 3 months ago.
I have a function which is technically a React Functional Component:
export default function Daw() {
return (
<>
<div>Hello world.</div>
</>
);
}
Of course, my ordinary function cannot have the ReactJS method of componentDidMount(). Since it is not a class which extends React.PureComponent.
I'm using this function inside a ReactJS web app.
export default function Daw() {
componentDidMount() { // ** Cannot use this ReactJS method!?
}
return (
<>
<div>Hello world.</div>
</>
);
}
Question
How can I possibly call componentDidMount() method of ReactJS inside my ordinary function? Is there a way to do it, without converting my function to a class which extends React.PureComponent? Is it possible?
First import useEffect from react
import { useEffect } from "react";
Then use useEffect with an empty dependency array,it is same as componentDidMount()
useEffect(() => { console.log("Mounted"); },[]);
Refer react official documentation for learning all lifecycle methods using useEffect hook:- https://reactjs.org/docs/hooks-effect.html
You're going to need React Hooks! All life-cycle methods we were doing in class components are available in functional components too via React Hooks, even in a better way. Read more about React hooks here: https://reactjs.org/docs/hooks-intro.html
And in this case, the equivalent of componentDidMount is this:
import { useEffect } from 'react'
export default function Daw() {
useEffect(() => {
// Code here will run just like componentDidMount
}, [])
return (
<>
<div>Hello world.</div>
</>
)
}
You can also learn about Effects in React by reading my article: A Beginner’s Guide to Effects in React
You cannot use componentDidMount() (class lifecycle methods) in React functional components. Instead you can use useEffect hook to perform the same operation. Like this:
useEffect(() => {
}, []);
Check here for more info - Similar Question
yes, you can use useEffect hook.
useEffect has the following abilities of class methods .i.e. componentDidMount, componentDidUpdate and componentWillUnmoun.
refer following info from official doc:
https://reactjs.org/docs/hooks-effect.html
I have a quite big React component SearchProvider written as a class and a UI component InputRange that I wrote as functional component using Hooks.
ATM I am getting the error "Invalid hook call. Hooks can only be called inside of the body of a function component."
Can I use the hook component as a child of the class component?
import { InputRange } from 'react-components';
class SearchProvider extends Component {
render() {
return <Fragment>
<InputRange />
{this.props.children}
</Fragment>;
}
function InputRange(props) {
...
useEffect(_ => { ...});
return <div className="input-range"></div>;
}
I answer my own question. The problem was duplicated react and not directly related to hooks. See https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react
I had to declare react and react-dom in the UI component as peerDependencies. This solves the problem.
I have the following react component:
class Cmp extends React.Component {
render () {
return <h3>{this.props.title}</h3>;
}
}
But I would like to expose or say to the consumer of my component to use it with a title otherwise it does not work the component.
Consumer would use it like
<Cmp title='Some fancy title' />
I need the consumer of my component to know that he should provide a title otherwise the component does not have any sense.
You can use PropTypes and set it to isRequired. You can also check if the prop is set at componentWillReceiveProps() and throw your error.
If you return null from a render method, nothing is rendered. You could use this knowledge to conditionally check if the prop is passed, and return null if the prop is not passed. The advantage here over using componentWillReceiveProps() is that you could use a functional component rather than a class component.
In rare cases you might want a component to hide itself even though it
was rendered by another component. To do this return null instead of
its render output.
Preventing Component from Rendering
Realistically you would also use PropTypes.
Cmp.propTypes = {
title: PropTypes.string.isRequired
};
Short Example
import React from 'react';
import PropTypes from 'prop-types';
const Cmp = (props) => props.title ? <h3>{props.title}</h3> : null
Cmp.propTypes = {
title: PropTypes.string.isRequired
}
export default Cmp;
I am currently building an app with React, React Router and React Redux
Versions:
React - v15.5.4
React Router - v4.0
React Redux - v.5.0.6
I am new to React and even newer to Redux and right when I got my head around the connect HOC I started to have this error that I cant seem to figure out.
When I connect a component to my redux store after a <switch> element and some <Route> elements. My connect within that returns my props as false boolean values where as the component within the connect has the correct props.
See code and error below for example.
Component
UserDashboardPage = connect(state => {
console.log("STATE", state);
return {
user: state.user.user,
userAuth: state.user.userAuth,
userFetched: state.user.fetched
};
})(UserDashboardPage);
UserDashboardPage.propTypes = {
user: PropTypes.shape(),
userAuth: PropTypes.shape(),
userFetched: PropTypes.boolean,
dispatch: PropTypes.func
};
CONSOLE LOG STATE
Connect with boolean prop values
Component with correct props
ERROR:
You are overwriting the local UserDashboardPage variable with the result of calling connect(). You then set PropTypes on the component returned by connect().
While you can do that, what you want in this case is to set the PropTypes of the wrapped component, not the wrapper component. Just swapping the order of execution will do it:
UserDashboardPage.propTypes = {
};
UserDashboardPage = connect(state => {
...
})(UserDashboardPage);
But you may want to consider using a different variable name for one component or the other, e.g.
UserDashboardPage.propTypes = {
};
const ConnectedUserDashboardPage = connect(state => {
...
})(UserDashboardPage);
This is usually not a problem since most people just immediately export the connected component as the default export:
export default connect(...)
The false values you're seeing are from React assigning default values to those props that failed validation. And they will always fail validation since those props are pulled from context, not passed down as normal props.
why are you passing UserDashboardPage into connect? This should be your non connected component
I have a react component that wraps a class that renders WebGL using three.js with the DOM and connects mobx store value and it changes with the class lifecycle methods.
The passed in mobx store is only used outside of the components render function in lifecycle functions (componentDidMount, componentDidUpdate, ..). Noticed that when the store changes, the component doesn't trigger a rerender. But I make a useless read within the render functions, such as in the example below passing a triggerRerenderListenerProp={this.props.store.debugSettings.showStats} prop to the div, the component becomes active only to store.debugSettings.showStats changes.
Is there a way of making the component listen to store changes wihtout using the store itself in the render function?
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import MapPreview from 'classes/MapPreview';
import style from './Preview.css';
class Preview extends Component {
static propTypes = {
store: PropTypes.object.isRequired,
imageUrl: PropTypes.string.isRequired
};
constructor (props) {
super(props);
this.containerEl = null;
}
componentDidMount () {
const options = {
debugSettings: this.props.store.debugSettings,
previewSettings: this.props.store.previewSettings
};
this.preview = new MapPreview(this.containerEl, options);
this.preview.setImage(imageUrl);
}
componentDidUpdate () {
this.preview.updateOptions({
debugSettings: this.props.store.debugSettings,
previewSettings: this.props.store.previewSettings
});
}
render () {
return (
<div
className={style.normal}
ref={(el) => { this.containerEl = el; }}
triggerRerenderListenerProp={this.props.store.debugSettings.showStats}
/>
);
}
}
export default observer(Preview);
The problem ultimately has two issues:
One, React is designed to only re-render when state or prop data changes.
Two, with mobx-react, I'm pretty sure the whole point is that the component won't re-render unless you dereference an observable value.
So while your props are technically changing, React doesn't do a deep object comparison of the props.
What you might try is setting options as internal component state -- that might force a re-render even though nothing in the render method would have changed.
The caveat here is that the updated props (from your store) might be too deeply nested as to force React to re-render even while updating internal state. You might also need to piggy-back on shouldComponentUpdate();