How to add additional props to a React element passed in as a prop?

Pass in the component constructor instead of an instance: class Menu extends React.Component { render() { return( <div className=”Menu”> <MenuItem icon={MdInbox} /> <MenuItem icon={MdDrafts} /> <MenuItem icon={MdTrash} /> </div> ); } } The child class: class MenuItem extends React.Component { render() { // This constant must begin with a capital, // it’s how React distinguishes … Read more

Passing props into external stylesheet in React Native?

I rather to have my styles in a separate file styles.js. Inside styles.js: export const styles = (props) => StyleSheet.create({ icon : { color: props.iconColor, fontSize: props.iconSize } } Inside your main class you can pass the value return ( <Icon style={styles(this.props).icon} /> ); Alternatively you can those value directly so it would be export … Read more

How can I add unique keys to React/Material UI Autocomplete component?

You can define your own renderOption that can return the list item with a correct key value. Your code complains about the duplicated keys because by default, Autocomplete uses the getOptionLabel(option) to retrieve the key: <Autocomplete renderOption={(props, option) => { return ( <li {…props} key={option.id}> {option.name} </li> ); }} renderInput={(params) => <TextField {…params} label=”Movie” />} … Read more

React Native what exactly is the (empty) component

It’s the React shortcut for Fragment component. You can write like this : import React, { Component } from ‘react’ class Component extends Component { render() { return <> <ComponentA/> <ComponentB/> </> } } Or without the shortcut and import Fragment component import React, { Component, Fragment } from ‘react’ class Component extends Component { … Read more

Using styled-components with props and TypeScript

There have been some recent developments and with a new version of Typescript (eg. 3.0.1) and styled-components (eg. 3.4.5) there’s no need for a separate helper. You can specify the interface/type of your props to styled-components directly. interface Props { onPress: any; src: any; width: string; height: string; } const Icon = styled.Image<Props>` width: ${p … Read more

Correct way to create event handlers using hooks in React?

I wouldn’t recommend either useState or useRef. You don’t actually need any hook here at all. In many cases, I’d recommend simply doing this: const MyComponent = () => { const handleClick = (e) => { //… } return <button onClick={handleClick}>Click Me</button>; }; However, it’s sometimes suggested to avoid declaring functions inside a render function … Read more