0

In version 0.13.x version of react-router, functions could be passed to child components of the RouteHandler as a prop by doing something like:

<RouteHandler foo={this.foo} {...this.state} />

I have recently upgraded to version 1.0.0 and found that the new syntax does not let me attach functions:

{React.cloneElement(this.props.children, {...this.state}, foo={this.foo})}

The code above throws a compilation error as foo={this.foo} is an unexpected token (I am aware that foo={this.foo} does not belong here, but where do I put it now?).

How do I attach functions to the component so that I can invoke them from child components? My use case here is that I want my child components to be able to invoke an emit event which will tell the server to push a notification to connected sockets, which will synchronise with connected clients.

Any help would be appreciated.

1 Answer 1

1

The signature of React.cloneElement (docs) is as follows:

React.cloneElement(element: ReactElement|ReactElement[], props: object)

As a result, your call isn't going to work - never mind the fact it is invalid syntax. What you're looking for is something a bit like this:

React.cloneElement(this.props.children, merge(this.state, this.foo))

Where merge is a function that can combine N many objects together (hopefully you realise you may end up with clobbering). For extra points, you may want to use an immutable merge. If you're using immutable (you are, right?), you could do that like this:

import {Map} from 'immutable'

const newProps = Map(this.state).merge(Map({ foo: this.foo }))
return React.cloneElement(this.props.children, newProps)

That might be a bit overkill for you, though.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.