Constrain allowed children in React TypeScript - reactjs

Using TypeScript in a React project is there any way to enforce some constraints on the allowed children of a component? Compile-time is preferred, but run-time could still be helpful.
In my case I have a component, call it <ClickTracker>, and it expects a single child with a callback prop onClick and it adds some extra functionality to the callback (tracking the click in an external library).
This works great as long as the child inside a <ClickTracker> does actually make use of an onClick prop (all HTML elements implement this, for example), but fails silently otherwise.
For example, this works:
<ClickTracker>
<div>Hello</div>
</ClickTracker>
But this doesn't work:
class Hello extends Component<{}, {}> {
render() {
return <div>Hello</div>
}
}
<ClickTracker>
<Hello />
</ClickTracker>
But this does work because it passes onClick to an HTML element:
class Hello extends Component<{onClick: MouseEventHandler}, {}> {
render() {
return <div onClick={this.props.onClick}>Hello</div>
}
}
<ClickTracker>
<Hello />
</ClickTracker>
As you can see I would like to have some safety around what can go inside <ClickTracker> based on the child props. Or if there's another way this could be done.

There is currently, no possible way of enforcing the children type with TypeScript.
There is more information in this issue.

Or if there's another way this could be done
Click events bubble up unless some component stopped propogation (not the default behavior for native components). So you can:
<div onClick={()=>alert('still noted')}>
<Hello />
</div>
And that div is your ClickTracker 🌹

Related

when should I pass 'className' props to react component?

Some react components pass the className props to the child component.
I haven't seen any need for passing className as a prop in my projects.
why this className props is been used ? and when should i adopt this approach?
import styled from 'styled-components'
const ReactComponent = ({ className }) => {
return <div className={className}/>
}
const StyledComponent = styled(ReactComponent)``;
It really depends on the context, but generally, the className prop is passed down from parent to child to either overwrite, or append the existing className on the child component.
This is particularly useful in the scenario when you are building reusable base components which needed to be easily extended and customised.
Given your example,
const ReactComponent = ({ className }) => {
return <div className={className}/>
}
Let's say we have a parent component which renders the child ReactComponent, and we need to customise the stylings for this instance:
return (
<div className='container'>
<ReactComponent className='is-red' />
<ReactComponent className='is-blue'/>
</div>
)
This will allow the parent to render both components, with different styles, and without the need to repeat the same code.
You generally add classes to create a style or JavaScript code snippet that effects more than one element. Here is an explanation of how to use classes.
This particular component uses StyledComponent, but it's possible that the user wanted to add a class to add extra styles on top of those for the default in specific cases.
It's also possible that the classes are used to toggle some effect in JS. I've linked examples of each case.
Without more code it's hard to say why this particular user passed down a className, but there are certainly cases where you could want to, or when you could do without passing down a className. If your code doesn't seem to require it, there's definitely no reason to add it in.

[react]: Intuitively Transclude another Component

Say I have a component Parent
<Parent>
<Component1 prop1={prop1} prop2={prop2}/>
<Component2 prop3={prop3} />
</Parent>
Normally, passing prop1,2, and 3 would render a perfectly usable Parent component. However, I want this component to be just as intuitive and dynamic like the components in ui libraries (for example, antd does this).
I would like to give the developer the option of transcluding his own component1. His usage would look a little like this:
<Parent prop3={prop3}>
<Component1>
<div> {prop1} </div>
<div> {prop2} </div>
</Component1>
</Parent>
So my questions are:
How would I allow possible? transclusion of a specific component on my component?
is this okay(not necessarily good, but practical) practice?
Thanks!
I think it is perfectly fine to do so if that's what you want for your API. It is also pretty simple.
To achieve this you need to use props.children. It will then include whatever is in between the opening and closing tag of the component:
In your example, then render function of Component would be:
render() {
return <div className="outer-shell">
{this.props.children}
</div>
}
You can use the parent component as a container which can hold other components.
class Parent extends Component{
render(){
return <div>{this.props.children}</div>
}
}
And this can be used like,
class SomeComponent{
render(){
return <Parent><Child1/><Child2></Parent>
}
}

REACT Warning Unknown props parsing to child component [duplicate]

I've built my own custom react-bootstrap Popover component:
export default class MyPopover extends Component {
// ...
render() {
return (
<Popover {...this.props} >
// ....
</Popover>
);
}
}
The component is rendered like so:
// ... my different class ...
render() {
const popoverExample = (
<MyPopover id="my-first-popover" title="My Title">
my text
</MyPopover >
);
return (
<OverlayTrigger trigger="click" placement="top" overlay={popoverExample}>
<Button>Click Me</Button>
</OverlayTrigger>
);
}
Now, I want to add custom props to MyPopover component like that:
my text
And to use the new props to set some things in the popover
for example -
<Popover {...this.props} className={this.getClassName()}>
{this.showTheRightText(this.props)}
</Popover>
but then I get this warning in the browser:
Warning: Unknown props popoverType on tag. Remove these props from the element.
Now, I guess that I can just remove the {...this.props} part and insert all the original props one by one without the custom props, but In this way I lose the "fade" effect and also it's an ugly way to handle this problem. Is there an easier way to do it?
Updated answer (React v16 and older):
As of React v16, you can pass custom DOM attributes to a React Component. The problem/warning generated is no longer relevant. More info.
Original answer (React v15):
The easiest solution here is to simply remove the extra prop before sending it to the Popover component, and there's a convenient solution for doing that.
export default class MyPopover extends Component {
// ...
render() {
let newProps = Object.assign({}, this.props); //shallow copy the props
delete newProps.popoverType; //remove the "illegal" prop from our copy.
return (
<Popover {...newProps} >
// ....
</Popover>
);
}
}
Obviously you can (and probably should) create that variable outside your render() function as well.
Basically you can send any props you want to your own component, but you'd have to "clean" it before passing it through. All react-bootstrap components are cleansed from "illegal" props before being passed as attributes to the DOM, however it doesn't handle any custom props that you may have provided, hence why you have to do your own bit of housekeeping.
React started throwing this warning as of version 15.2.0. Here's what the documentation says about this:
The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.
[...]
To fix this, composite components should "consume" any prop that is intended for the composite component and not intended for the child component.
For further reading, check this page from the official react site.

Add custom props to a custom component

I've built my own custom react-bootstrap Popover component:
export default class MyPopover extends Component {
// ...
render() {
return (
<Popover {...this.props} >
// ....
</Popover>
);
}
}
The component is rendered like so:
// ... my different class ...
render() {
const popoverExample = (
<MyPopover id="my-first-popover" title="My Title">
my text
</MyPopover >
);
return (
<OverlayTrigger trigger="click" placement="top" overlay={popoverExample}>
<Button>Click Me</Button>
</OverlayTrigger>
);
}
Now, I want to add custom props to MyPopover component like that:
my text
And to use the new props to set some things in the popover
for example -
<Popover {...this.props} className={this.getClassName()}>
{this.showTheRightText(this.props)}
</Popover>
but then I get this warning in the browser:
Warning: Unknown props popoverType on tag. Remove these props from the element.
Now, I guess that I can just remove the {...this.props} part and insert all the original props one by one without the custom props, but In this way I lose the "fade" effect and also it's an ugly way to handle this problem. Is there an easier way to do it?
Updated answer (React v16 and older):
As of React v16, you can pass custom DOM attributes to a React Component. The problem/warning generated is no longer relevant. More info.
Original answer (React v15):
The easiest solution here is to simply remove the extra prop before sending it to the Popover component, and there's a convenient solution for doing that.
export default class MyPopover extends Component {
// ...
render() {
let newProps = Object.assign({}, this.props); //shallow copy the props
delete newProps.popoverType; //remove the "illegal" prop from our copy.
return (
<Popover {...newProps} >
// ....
</Popover>
);
}
}
Obviously you can (and probably should) create that variable outside your render() function as well.
Basically you can send any props you want to your own component, but you'd have to "clean" it before passing it through. All react-bootstrap components are cleansed from "illegal" props before being passed as attributes to the DOM, however it doesn't handle any custom props that you may have provided, hence why you have to do your own bit of housekeeping.
React started throwing this warning as of version 15.2.0. Here's what the documentation says about this:
The unknown-prop warning will fire if you attempt to render a DOM element with a prop that is not recognized by React as a legal DOM attribute/property. You should ensure that your DOM elements do not have spurious props floating around.
[...]
To fix this, composite components should "consume" any prop that is intended for the composite component and not intended for the child component.
For further reading, check this page from the official react site.

When should I be using React.cloneElement vs this.props.children?

I am still a noob at React and in many examples on the internet, I see this variation in rendering child elements which I find confusing. Normally I see this:
class Users extends React.Component {
render() {
return (
<div>
<h2>Users</h2>
{this.props.children}
</div>
)
}
}
But then I see an example like this:
<ReactCSSTransitionGroup
component="div"
transitionName="example"
transitionEnterTimeout={500}
transitionLeaveTimeout={500}
>
{React.cloneElement(this.props.children, {
key: this.props.location.pathname
})}
</ReactCSSTransitionGroup>
Now I understand the api but the docs don't exactly make clear when I should be using it.
So what does one do which the other can't? Could someone explain this to me with better examples?
props.children isn't the actual children; It is the descriptor of the children. So you don't have actually anything to change; you can't change any props, or edit any functionality; you can only read from it. If you need to make any modifications you have to create new elements using React.CloneElement.
https://egghead.io/lessons/react-use-react-cloneelement-to-extend-functionality-of-children-components
An example:
main render function of a component such as App.js:
render() {
return(
<Paragraph>
<Sentence>First</Sentence>
<Sentence>Second</Sentence>
<Sentence>Third</Sentence>
</Paragraph>
)
}
now let's say you need to add an onClick to each child of Paragraph; so in your Paragraph.js you can do:
render() {
return (
<div>
{React.Children.map(this.props.children, child => {
return React.cloneElement(child, {
onClick: this.props.onClick })
})}
</div>
)
}
then simply you can do this:
render() {
return(
<Paragraph onClick={this.onClick}>
<Sentence>First</Sentence>
<Sentence>Second</Sentence>
<Sentence>Third</Sentence>
</Paragraph>
)
}
Note: the React.Children.map function will only see the top level elements, it does not see any of the things that those elements render; meaning that you are providing the direct props to children (here the <Sentence /> elements). If you need the props to be passed down further, let's say you will have a <div></div> inside one of the <Sentence /> elements that wants to use the onClick prop then in that case you can use the Context API to do it. Make the Paragraph the provider and the Sentence elements as consumer.
Edit:
Look at Vennesa's answer instead, which is a better explanation.
Original:
First of all, the React.cloneElement example only works if your child is a single React element.
For almost everything {this.props.children} is the one you want.
Cloning is useful in some more advanced scenarios, where a parent sends in an element and the child component needs to change some props on that element or add things like ref for accessing the actual DOM element.
In the example above, the parent which gives the child does not know about the key requirement for the component, therefore it creates a copy of the element it is given and adds a key based on some unique identifier in the object. For more info on what key does: https://facebook.github.io/react/docs/multiple-components.html
In fact, React.cloneElement is not strictly associated with this.props.children.
It's useful whenever you need to clone react elements(PropTypes.element) to add/override props, without wanting the parent to have knowledge about those component internals(e.g, attaching event handlers or assigning key/ref attributes).
Also react elements are immutable.
React.cloneElement( element, [props], [...children] ) is almost equivalent to:
<element.type {...element.props} {...props}>{children}</element.type>
However, the children prop in React is especially used for containment (aka composition), pairing with React.Children API and React.cloneElement, component that uses props.children can handle more logic(e.g., state transitions, events, DOM measurements etc) internally while yielding the rendering part to wherever it's used, React Router <switch/> or compound component <select/> are some great examples.
One last thing that worth mentioning is that react elements are not restricted to props.children.
function SplitPane(props) {
return (
<div className="SplitPane">
<div className="SplitPane-left">
{props.left}
</div>
<div className="SplitPane-right">
{props.right}
</div>
</div>
);
}
function App() {
return (
<SplitPane
left={
<Contacts />
}
right={
<Chat />
} />
);
}
They can be whatever props that makes sense, the key was to define a good contract for the component, so that the consumers of it can be decoupled from the underlying implementation details, regardless whether it's using React.Children, React.cloneElement, or even React.createContext.

Resources