Warning: Functions are not valid as a React child HOC - javascript

I'm writing an HOC in Reactjs. When I'm going to return class in WithErrorHandler HOC I get a warning in console said
"Functions are not valid as a React child. This may happen if you
return a Component instead of <Component /> from render. Or maybe you
meant to call this function rather than return it." However, if I
remove class, warning will be gone.
I am going to add click handler for Modal to enable it to close. Also, I am going to get message from error which I have passed as an argument of second function for show in Modal.
import React, { Component } from 'react';
import Modal from '../Modal'
const WithErrorHandler = WrappedComponent => ({ error, children }) => {
return(
class extends Component {
state = {modalShow: false}
modalToggle = ()=> {
this.setState(ModalShow: !!error.message)}
render() {
return (
<WrappedComponent>
{error && <Modal type={error.messageType} message={error.message} />}
{children}
</WrappedComponent>
);
}
}
)
};
const DivWithErrorHandling = WithErrorHandler(({children}) => {
return children
})
class App extends Component {
state ={error: null}
someMethode = ()=> {
const sampleError = {//an object with message key}
this.setState(error: sampleError)
}
Render(){
return (
<DivWithErrorHandling error={this.state.error} >
<h1>Component</h1>
<button onClick={this.someMethode}>
Toggle Error
</button>
</DivWithErrorHandling>
)
}
}

Your HOC is accepting actual component & returning a children function(wrapper component) which again returns a class component.
Instead of that your HOC should accept actual component & return a new wrapped component.
This should probably fix your issue.
const WithErrorHandler = WrappedComponent => ({ error, children }) => {
return(
<WrappedComponent>
{error && <Modal type={error.messageType} message={error.message} />}
{children}
</WrappedComponent>
);
};

HOC is a function that takes a component and returns a new component
Your code:
const WithErrorHandler
= WrappedComponent // takes a component
=> ({ error, children }) // takes some params
=> class ... // returns a new component
What you actually want:
const WithErrorHandler
= WrappedComponent // takes a component
=> class ... // returns a new component
// inside the class use this.props.error, this.props.children, etc.
Another way (using a functional component):
const WithErrorHandler
= WrappedComponent // takes a component
=> ({ error, children }) => <WrappedComponent>...</WrappedComponent> // returns a new component

Related

2 way event-binding between parent and child components is not working

Working with an array of mapped items, I am attempting to toggle class in a child component, but state change in the parent component is not passed down to the child component.
I've tried a couple different approaches (using {this.personSelectedHandler} vs. {() => {this.personSelectedHandler()} in the clicked attribute, but neither toggled class successfully. The only class toggling I'm able to do affects ALL array items rendered on the page, so there's clearly something wrong with my binding.
People.js
import React, { Component } from 'react';
import Strapi from 'strapi-sdk-javascript/build/main';
import Person from '../../components/Person/Person';
import classes from './People.module.scss';
const strapi = new Strapi('http://localhost:1337');
class People extends Component {
state = {
associates: [],
show: false
};
async componentDidMount() {
try {
const associates = await strapi.getEntries('associates');
this.setState({ associates });
}
catch (err) {
console.log(err);
}
}
personSelectedHandler = () => {
const currentState = this.state.show;
this.setState({
show: !currentState
});
};
render() {
return (
<div className={classes.People}>
{this.state.associates.map(associate => (
<Person
name={associate.name}
key={associate.id}
clicked={() => this.personSelectedHandler()} />
))}
</div>
);
}
}
export default People;
Person.js
import React from 'react';
import classes from './Person.module.scss';
const baseUrl = 'http://localhost:1337';
const person = (props) => {
let attachedClasses = [classes.Person];
if (props.show) attachedClasses = [classes.Person, classes.Active];
return (
<div className={attachedClasses.join(' ')} onClick={props.clicked}>
<img src={baseUrl + props.photo.url} alt={props.photo.name} />
<p>{props.name}</p>
</div>
);
};
export default person;
(Using React 16.5.0)
First of all, in your People.js component, change your person component to:
<Person
name={associate.name}
key={associate.id}
clicked={this.personSelectedHandler}
show={this.state.show}}/>
You were not passing the prop show and also referring to a method inside the parent class is done this way. What #Shawn suggested, because of which all classes were toggled is happening because of Event bubbling.
In your child component Person.js, if you change your onClick to :
onClick={() => props.clicked()}
The parenthesis after props.clicked executes the function there. So, in your personSelectedHandler function, you either have to use event.preventDefault() in which case, you also have to pass event like this:
onClick={(event) => props.clicked}
and that should solve all your problems.
Here's a minimal sandbox for this solution:
CodeSandBox.io

How can I render a different component based on a value from the Context API?

So I have this navigator component where depending on a value coming from another component, I need to show a different bottom navigation.
For now I am getting an error on the context consumer, here:
import { ThemeProvider, ThemeConsumer } from '../context/some';
const SelectedRoute = () => (
<ThemeConsumer>
{context => (context ? MainTabNavigator : PickupNavigator)}
</ThemeConsumer>
);
export default createAppContainer(
createSwitchNavigator(
{
App: SelectedRoute,
},
),
);
This is the only thing I have to create context:
const ThemeContext = React.createContext(0);
export const ThemeProvider = ThemeContext.Provider;
export const ThemeConsumer = ThemeContext.Consumer;
I am getting this warning:
Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
What can I do to render what I need correctly?
You want to return JSX from the function given as child to ThemeConsumer, not just return a component.
const SelectedRoute = () => (
<ThemeConsumer>
{context => (context ? <MainTabNavigator /> : <PickupNavigator />)}
</ThemeConsumer>
);
I have not run the example, but just suggesting from the docs. I thought the explanation was pretty clear but I could be wrong.
Just define a context variable in a separate file, in your case like this:
export const IndexContext = React.createContext({
indexValue: value,
toggleNavigator: () => {},
});
In your component(which receives indexValue), you can use the context value and toggle accordingly:
<ThemeContext.Consumer>
{({indexValue, toggleNavigator}) => (
// your component which uses the theme
)}
</ThemeContext.Consumer>
Since your component A is a stateful component, you can handle changes and update the context value there.
class App extends React.Component {
constructor(props) {
super(props);
this.toggleIndex = () => {
this.setState({ index });
this.handleStateIndexChange();
MY_CONTEXT = index;
};
// State also contains the updater function so it will
// be passed down into the context provider
this.state = {
index: index,
toggleIndex: this.toggleIndex,
};
}
render() {
// The entire state is passed to the provider
return (
<IndexContext.Provider value={this.state}>
<Content />
</IndexContext.Provider>
);
}
}
I hope this helps.

Why this error is showing: "A valid React element (or null) must be returned. You may have returned undefined"

I know this question has been answered but i just cannot handle what's going so wrong. I'm having a wrapper function:
const withTracker = (WrappedComponent, partnerTrackingCode, options = {}) => {
const trackPage = (page) => {
ReactGA.set({
page,
options
});
ReactGA.pageview(page);
};
class HOC extends Component {
componentDidMount() {
ReactGA.initialize(partnerTrackingCode);
const page = this.props.location.pathname;
trackPage(page);
}
componentWillReceiveProps(nextProps) {
const currentPage = this.props.location.pathname;
const nextPage = nextProps.location.pathname;
if (currentPage !== nextPage) {
trackPage(nextPage);
}
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return HOC;
};
export default withTracker;
and i'm calling it here:
export default (props) => {
const MainComponent = (
<div>
...
</div>
);
if (props.partnerTrackingCode) {
return (
withTracker(MainComponent, props.partnerTrackingCode)
);
}
return (<div />);
};
When the tracking code is defined and the withTracker is called even if mainComponent is a component it shows me this error: A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object
I've also try to replace the WrappedComponent with an empty div:
return(<div />)
but still the same error
It looks like you're confusing elements and components here. You're passing around elements (the actual output you want to be rendered), whereas a HOC is a component (a function that generally takes a set of props and returns an element). You're passing an element to your HOC, so when it tries rendering it (in the HOC render function) it can't render it and you get the error.
To fix, you'd firstly need to make your MainComponent into an actual component instead of just the element you want it to return, e.g.:
const MainComponent = props => (
<div>
...
</div>
)
Then to use that with your wrapper you'd want to wrap and then render that:
if (props.partnerTrackingCode) {
const MainWithTracker = withTracker(MainComponent, props.partnerTrackingCode)
return <MainWithTracker />;
}
This is a bit weird though, as you need to create the wrapped component within your render method, which isn't how you'd normally do things. It might make more sense to change your HOC so that it returns a component that takes the partnerTrackingCode as a prop instead of an argument to your HOC. Something along the lines of:
// your HOC (omitting irrelevant bits)
const withTracker = (WrappedComponent, options = {}) => {
...
class HOC extends Component {
componentDidMount() {
ReactGA.initialize(this.props.partnerTrackingCode);
...
}
...
render() {
// pull out the tracking code so it doesn't get passed through to the
// wrapped component
const { partnerTrackingCode, ...passthrough } = this.props;
return <WrappedComponent {...passthrough} />;
}
}
return HOC;
};
// in your component
const MainComponent = props => (
<div>
...
</div>
);
const MainWithTracker = withTracker(MainComponent);
export default (props) => {
if (props.partnerTrackingCode) {
return (<MainWithTracker partnerTrackingCode={props.partnerTrackingCode} />);
}
return (<div />);
};
(I don't think this is the best way to do it, I've just tried keeping as close to your code as I could. Once you start restructuring it, with your better knowledge of exactly what you're trying to do you may find a better way to organise it.)
your problem in your return method , in first step you must be know
when you want call HOC , you must write like this
return withTracker(MainComponent, props.partnerTrackingCode)
instead this
return (
withTracker(MainComponent, props.partnerTrackingCode)
);
remove ()
and then check again , if you still have error tell me

Higher Order Component in DOM to Wrap functionality

I need to wrap functionality in a, lets say button. However when I call the HOC in the render method of another component I get nothing.
I have this HOC
import React,{Component,PropTypes} from 'react';
export let AddComment = (ComposedComponent) => class AC extends React.Component {
render() {
return (
<div class="something">
Something...
<ComposedComponent {...this.props}/>
</div>
);
}
}
and trying to do this
import {AddComment} from '../comments/add.jsx';
var Review = React.createClass({
render: function(){
return (
<div className="container">
{AddComment(<button>Add Comment</button>,this.props)}
</div>
});
module.exports = Review;
I want AddComment to open a Dialog and submit a comments form when I click the button. I need AddComment to be available other components throughtout the app.
Is the HOC pattern correct? How can I easily accomplish this?
Thanks
To summarize really quick: What are higher-order components?
Just a fancy name for a simple concept: Simply put: A component that takes in a component and returns you back a more enhanced version of
the component.
We are essentially enhancing a component.
Accepts a function that maps owner props to a new collection of props
that are passed to the base component.
We are basically passing the props down from that BaseComponent down
to the Wrapped Component so that we can have them available in that
child component below:
Use to compose multiple higher-order components into a single
higher-order component.
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { AddComment } from '../comments/add.jsx';
const mapProps = propFunction => Component => (props) => {
return React.createFactory(Component)(propFunction(props));
};
const compose = (propFunction, ComponentContainer) => (BaseComponent) => {
return propFunction(ComponentContainer(BaseComponent));
};
const Review = AddComment(({ handleReviewToggle }) => (
<div className="container">
<ReviewButton
primaryText="Add Comment"
_onClick={handleReviewToggle}
/>
</div>
));
export default Review;
// ================================================================== //
const EnhanceReview = compose(withProps, AddComment)(Review);
const withProps = mapProps(({ ...props }) => ({ ...props }));
The AddComment Container that will have the button and the dialog itself.
export function AddComment(ComposedComponent) {
class AC extends React.Component {
constructor() {
super();
this.state = {open: false};
}
handleReviewToggle = () => {
this.setState({ open: !this.state.open })
}
render() {
return (
<ComposedComponent
{...this.props}
{...this.state}
{...{
handleReviewToggle: this.handleReviewToggle,
}}
/>
);
}
}
export default AddComment;
// ==================================================================
The ReviewButton Button that will fire an event to change state true or false.
const ReviewButton = ({ _onClick, primaryText }) => {
return (
<Button
onClick={_onClick}
>
{primaryText || 'Default Text'}
</Button>
);
};
export default ReviewButton;
// ================================================================== //
However this was all done without using a library. There's one out called recompose here: https://github.com/acdlite/recompose. I highly suggest that you try it out without a library to get a good understanding of Higher Order Components.
You should be able to answer these questions below after playing with Higher Order components:
What is a Higher Order Component?
What are the disadvantages of using HOC? What are some use cases?
How will this improve performance? And how can I use this to optimize for performance?
When is the right time to use a HOC?

React: Passing props to function components

I have a seemingly trivial question about props and function components. Basically, I have a container component which renders a Modal component upon state change which is triggered by user click on a button. The modal is a stateless function component that houses some input fields which need to connect to functions living inside the container component.
My question: How can I use the functions living inside the parent component to change state while the user is interacting with form fields inside the stateless Modal component? Am I passing down props incorrectly?
Container
export default class LookupForm extends Component {
constructor(props) {
super(props);
this.state = {
showModal: false
};
}
render() {
let close = () => this.setState({ showModal: false });
return (
... // other JSX syntax
<CreateProfile fields={this.props} show={this.state.showModal} onHide={close} />
);
}
firstNameChange(e) {
Actions.firstNameChange(e.target.value);
}
};
Function (Modal) Component
const CreateProfile = ({ fields }) => {
console.log(fields);
return (
... // other JSX syntax
<Modal.Body>
<Panel>
<div className="entry-form">
<FormGroup>
<ControlLabel>First Name</ControlLabel>
<FormControl type="text"
onChange={fields.firstNameChange} placeholder="Jane"
/>
</FormGroup>
);
};
Example: say I want to call this.firstNameChange from within the Modal component. I guess the "destructuring" syntax of passing props to a function component has got me a bit confused. i.e:
const SomeComponent = ({ someProps }) = > { // ... };
You would need to pass down each prop individually for each function that you needed to call
<CreateProfile
onFirstNameChange={this.firstNameChange}
onHide={close}
show={this.state.showModal}
/>
and then in the CreateProfile component you can either do
const CreateProfile = ({onFirstNameChange, onHide, show }) => {...}
with destructuring it will assign the matching property names/values to the passed in variables. The names just have to match with the properties
or just do
const CreateProfile = (props) => {...}
and in each place call props.onHide or whatever prop you are trying to access.
I'm using react function component
In parent component first pass the props like below shown
import React, { useState } from 'react';
import './App.css';
import Todo from './components/Todo'
function App() {
const [todos, setTodos] = useState([
{
id: 1,
title: 'This is first list'
},
{
id: 2,
title: 'This is second list'
},
{
id: 3,
title: 'This is third list'
},
]);
return (
<div className="App">
<h1></h1>
<Todo todos={todos}/> //This is how i'm passing props in parent component
</div>
);
}
export default App;
Then use the props in child component like below shown
function Todo(props) {
return (
<div>
{props.todos.map(todo => { // using props in child component and looping
return (
<h1>{todo.title}</h1>
)
})}
</div>
);
}
An addition to the above answer.
If React complains about any of your passed props being undefined, then you will need to destructure those props with default values (common if passing functions, arrays or object literals) e.g.
const CreateProfile = ({
// defined as a default function
onFirstNameChange = f => f,
onHide,
// set default as `false` since it's the passed value
show = false
}) => {...}
just do this on source component
<MyDocument selectedQuestionData = {this.state.selectedQuestionAnswer} />
then do this on destination component
const MyDocument = (props) => (
console.log(props.selectedQuestionData)
);
A variation of finalfreq's answer
You can pass some props individually and all parent props if you really want (not recommended, but sometimes convenient)
<CreateProfile
{...this.props}
show={this.state.showModal}
/>
and then in the CreateProfile component you can just do
const CreateProfile = (props) => {
and destruct props individually
const {onFirstNameChange, onHide, show }=props;

Categories