Unable to find an error - reactjs

i know it's a minor and maybe a fool question but i'm stuck for about an hour at an error which i cant see. This is my code:
const ModalRoot = ({ modalType, modalProps, locale }) => {
if (!modalType) {
return <span />;
}
return (
<IntlProvider
locale={locale}
key={locale}
messages={messagesFor(locale)}
>
<div className="backdrop">
{renderAppropriateModal(modalType, modalProps)}
</div>
</IntlProvider>
);
};
The console shows an error in the if saying unexpected token. Why is this happening??

This can be your error...
check this samples.
Wrong place to declare.
import React from 'react';
class YOURCLASS extends React.Component {
constructor(props) {
super(props);
}
//do not place this ModalRoot here
const ModalRoot = ({ modalType, modalProps, locale }) => {
//contents
}
render(){
return(
<div>{yourContent}</div>
);
}
}
Right place to declare
import React from 'react';
//Place it here outside the class YOURCLASS
const ModalRoot = ({ modalType, modalProps, locale }) => {
//contents
}
class YOURCLASS extends React.Component {
constructor(props) {
super(props);
}
render(){
return(
<div>{yourContent}</div>
);
}
}
if you still intends to do it inside class... better use function instead...
import React from 'react';
class YOURCLASS extends React.Component {
constructor(props) {
super(props);
}
//function type ModalRoot
ModalRoot(modalType, modalProps, locale){
//contents
return <IntlProvider />;
}
render(){
const {modalType, modalProps, locale} = this.props;
let yourContent = this.ModalRoot(modalType, modalProps, locale);
return(
<div>{yourContent}</div>
);
}
}
hope it helps...

Related

Pass original component's function to react HOC

I have created react HOC component as below.
const UpdatedComponent = (OriginalComponent) => {
class NewComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
counter:0
}
}
componentDidMount(){
}
incrementCount = () => {
this.setState(prevState => {
return {counter:prevState.counter+1}
})
}
render(){
return <OriginalComponent
incrementCount={this.incrementCount}
count={this.state.counter}
/>
}
}
return NewComponent
}
export default UpdatedComponent
and I am using that component in the below example
class HoverCounter extends Component {
componentDidMount(){
}
handleMessages = () => {
// need to do somthing
}
render() {
const {incrementCount, count} = this.props
return (
<div onMouseOver={incrementCount}>
Hoverd {count} times
</div>
)
}
}
export default UpdatedComponent(HoverCounter)
I want to know that is it possible to pass
handleMessages()
function to HOC?
like this
export default UpdatedComponent(HoverCounter,handleMessages)
I have no idea how to pass the original component function or props to HOC.
you could get everyThing in your Hoc like this :
const UpdatedComponent = (OriginalComponent , func) => {
componentDidMount(){
func()
}
in HoverCounter also you could add this changes:
static handleMessages(){
// need to do something
}
export default UpdatedComponent(HoverCounter , HoverCounter.handleMessages)

State doesn't update when props changes

i was learning react from 'React docs' for few days and today i got into the trouble. Link to docs: https://reactjs.org/docs/conditional-rendering.html#element-variables.
Exercise is that when the button clicks text will change. In docs, they did it with functions and it works perfectly but i tried it with classes.
The problem is that state doesn't update when props changes, it only have its initial value. I'm struggling with it since 2 hours and didn't find the solution. I'm new to React so please be forbearance.
Code:
class UserGreeting extends React.Component {
render() {
return (
<h1>Welcome back!</h1>
);
}
}
class GuestGreeting extends React.Component {
render() {
return (
<h1>Please sign up!</h1>
);
}
}
class Greeting extends React.Component {
constructor(props) {
super(props);
this.state = {isLoggedIn: this.props.isLoggedIn};
}
render() {
let isLoggedIn = this.state.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
}
class LoginButton extends React.Component {
constructor(props) {
super(props);
this.state = {onClick: this.props.onClick};
}
render() {
return (
<button onClick={this.state.onClick}>Login</button>
);
}
}
class LogoutButton extends React.Component {
constructor(props) {
super(props);
this.state = {onClick: this.props.onClick};
}
render() {
return (
<button onClick={this.state.onClick}>Logout</button>
);
}
}
class LoginControl extends React.Component {
constructor(props) {
super(props);
this.state = {isLoggedIn: true};
}
handleLoginClick = () => {
this.setState({isLoggedIn: true});
}
handleLogoutClick = () => {
this.setState({isLoggedIn: false});
}
render() {
const isLoggedIn = this.state.isLoggedIn;
let button;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
}
}
ReactDOM.render(
<LoginControl />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You are storing your answer in the state in the Greeting component inside the constructor. The constructor will only be called once at mount component.
Change your Greeting component with below code**
class Greeting extends React.Component {
render() {
let isLoggedIn = this.props.isLoggedIn;
if (isLoggedIn) {
return <UserGreeting />;
}
return <GuestGreeting />;
}
}

Converting functional component to class component

I have one functional component, but as I need to use now state and more complex logic, I would like to convert it to class component.
But I don't know exactly how to get it working:
My functional component:
import React from 'react';
const FileList = (props) => {
const items = props.items.map((item) => {
return <p key={item.reqId} > { item.name }</ p>
});
return <div>{items}</div>
}
And I tried to do that:
export default class FileL extends React.Component {
constructor(props) {
super(props)
}
render() {
const { items } = this.props;
items = props.items.map((item) => {
return <p key={item.reqId} > {item.name}</ p>
});
return (
<div>{items}</div>
);
}
}
But this is not working.It says "items" is read-only.
I would like to keep the same functionality.
Any ideas?
In your render function
render() {
const { items } = this.props;
items = props.items.map((item) => {
return <p key={item.reqId} > {item.name}</ p>
});
return (
<div>{items}</div>
);
}
items is const so you can't override it. This has nothing to do with React. And you shouldn't reassign a props element, even if its defined with let. You might use the following:
render() {
const { items } = this.props;
return (
<div>
{
items.map((item) => <p key={item.reqId} > {item.name}</ p>)
}
</div>
);
}
You can try this,
export default class FileL extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{
this.props.items.map((item) => {
return <p key={item.reqId} > {item.name}</ p>
})
}
</div>
);
}
}
Actually you don't need to convert your component to class based component, as React 16.8 comes with Hooks. Using Hooks you can do whatever you can do with class based component. They let you use state and other React features without writing a class.

Is passing the _setTitle method with the props the way to go?

want to update the title present in the Header
everytime we navigate to a new page.
Is passing the _setTitle method with the props the way to go?
import React, { Component } from 'react';
import PropTypes from 'prop-types';
Main App component
export class App extends Component {
constructor() {
super();
this.state = { pageTitle: 'My app' };
this._setTitle = this._setTitle.bind(this);
}
_setTitle(title) {
this.setState({ pageTitle: title });
}
render() {
const { pageTitle } = this.state.pageTitle;
return (
<div>
<Header title={pageTitle} />
{React.cloneElement(children, { setTitle: this._setTitle })}
<Footer />
</div>
);
}
}
Header and Footer Components
export class Header extends Component {
static propTypes = {
title: PropTypes.string
};
// ...
render() {
const { title } = this.props;
return <h2>{title}</h2>;
}
}
export class Footer extends Component {
// Footer code
}
Following are the different page Components:
export class Profile extends Component {
static propTypes = {
setTitle: PropTypes.func.isRequired
};
componentWillMount() {
this.props.setTitle('Profile');
}
}
export class Projects extends Component {
static propTypes = {
setTitle: PropTypes.func.isRequired
};
componentWillMount() {
this.props.setTitle('Projects');
}
// ...
}
export class ProjectForm extends Component {
static propTypes = {
setTitle: PropTypes.func.isRequired
};
componentWillMount() {
this.props.setTitle('New Project');
}
// ...
}
export class Translators extends Component {
static propTypes = {
setTitle: PropTypes.func.isRequired
};
componentWillMount() {
this.props.setTitle('Translators');
}
// ...
}
// ...
How can I improve upon this. I'm new to react so pls suggest If you have any ideas, I'll implement it. Thank you.
You can make use of Context and pass the setTitle method as a Context value, then you can create a Component that has the logic of setting the Title, A simple implementation would look like
const TitleContext = React.createContext();
export class App extends Component {
constructor() {
super();
this.state = { pageTitle: 'My app' };
this._setTitle = this._setTitle.bind(this);
}
_setTitle(title) {
this.setState({ pageTitle: title });
}
render() {
const { pageTitle } = this.state.pageTitle;
return (
<TitleContext.Provider value={{setTitle: this._setTitle}}
<div>
<Header title={pageTitle} />
{this.props.children}
<Footer />
</div>
</TitleContext.Provider>
);
}
}
class TitleSetter extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired
}
componentDidMount() {
this.context.setTitle(this.props.title)
}
}
TitleSetter.contextTypes = TitleContext;
Now in any component you can simply render the TitleSetter like
export class Profile extends Component {
render() {
return (
<div>
<TitleSetter title="Profile" />
{/* other context */}
</div>
)
}
}
Also while looking into context, please look at the this question on how to access context outside of render

React Components inside fragment not loading

I'm using react 16.2.0 and react-dom 16.2.0. Following is the code I have.
import React, { Fragment } from 'react';
import BodyComponent from './BodyComponent';
import * as HeaderComponents from './HeaderComponent';
class TablePage extends React.Component {
constructor(props) {
super(props);
}
render() {
const MyHeader = (props) => {
const Header = HeaderComponents.TableHeader;
return <Header status={props.status}/>;
};
let pageContent = null;
pageContent = (
<ul className="list-table" role="table" aria-label={MessageConstants.ASSIGNMENT_ITEMS_TABLE_CAPTION_MESSAGE}>
<MyHeader status={status}/>
{
items.map((item, i) => {
return <TableBody dataSet={item} key={i}/>;
})
}
</ul>
);
return (pageContent);
}
}
class TableBody extends React.Component {
constructor(props) {
super(props);
}
render() {
const {dataSet} = this.props;
const BodyHeader = (props) => {
const Header = HeaderComponents.BodyHeader;
return <Header index={this.props.index}/>;
};
return (
<Fragment>
<BodyHeader index={this.props.index}/>
<BodyComponent itemList={dataSet.content}/>
</Fragment>
);
}
}
export default TablePage;
My problem is, the components I'm returning inside are not rendering. I don't get any errors in the console as well.
I tried rendering simple html code such as
<Fragment>
<p>foo</p>
<p>bar</p>
</Fragment>
But the issue remains. Can someone please help me with this.

Resources