-
What is the difference between
super()andsuper(props)in React using ES6 classes?When you want to access
this.propsinconstructor()then you should pass props tosuper()method.Using
super(props):class MyComponent extends React.Component { constructor(props) { super(props) console.log(this.props) // { name: 'John', ... } } }Using
super():class MyComponent extends React.Component { constructor(props) { super() console.log(this.props) // undefined } }Outside
constructor()both will display same value forthis.props. -
How to loop inside JSX?
You can simply use
Array.prototype.mapwith ES6 arrow function syntax.For example, the
itemsarray of objects is mapped into an array of components:<tbody> {items.map(item => <SomeComponent key={item.id} name={item.name} />)} </tbody>But you can't iterate using
forloop:<tbody> for (let i = 0; i < items.length; i++) { <SomeComponent key={items[i].id} name={items[i].name} /> } </tbody>This is because JSX tags are transpiled into function calls, and you can't use statements inside expressions. This may change thanks to
doexpressions which are stage 1 proposal. -
How do you access props in attribute quotes?
React (or JSX) doesn't support variable interpolation inside an attribute value. The below representation won't work:
<img className='image' src='images/{this.props.image}' />But you can put any JS expression inside curly braces as the entire attribute value. So the below expression works:
<img className='image' src={'images/' + this.props.image} />Using template strings will also work:
<img className='image' src={`images/${this.props.image}`} /> -
What is React proptype array with shape?
If you want to pass an array of objects to a component with a particular shape then use
React.PropTypes.shape()as an argument toReact.PropTypes.arrayOf().ReactComponent.propTypes = { arrayWithShape: React.PropTypes.arrayOf(React.PropTypes.shape({ color: React.PropTypes.string.isRequired, fontSize: React.PropTypes.number.isRequired })).isRequired } -
How to conditionally apply class attributes?
You shouldn't use curly braces inside quotes because it is going to be evaluated as a string.
<div className="btn-panel {this.props.visible ? 'show' : 'hidden'}">Instead you need to move curly braces outside (don't forget to include spaces between class names):
<div className={'btn-panel ' + (this.props.visible ? 'show' : 'hidden')}>Template strings will also work:
<div className={`btn-panel ${this.props.visible ? 'show' : 'hidden'}`}> -
What is the difference between React and ReactDOM?
The
reactpackage containsReact.createElement(),React.Component,React.Children, and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. Thereact-dompackage containsReactDOM.render(), and inreact-dom/serverwe have server-side rendering support withReactDOMServer.renderToString()andReactDOMServer.renderToStaticMarkup(). -
Why ReactDOM is separated from React?
The React team worked on extracting all DOM-related features into a separate library called ReactDOM. React v0.14 is the first release in which the libraries are split. By looking at some of the packages,
react-native,react-art,react-canvas, andreact-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM.To build more environments that React can render to, React team planned to split the main React package into two:
reactandreact-dom. This paves the way to writing components that can be shared between the web version of React and React Native. -
How to use React label element?
If you try to render a
<label>element bound to a text input using the standardforattribute, then it produces HTML missing that attribute and prints a warning to the console.<label for={'user'}>{'User'}</label> <input type={'text'} id={'user'} />Since
foris a reserved keyword in JavaScript, usehtmlForinstead.<label htmlFor={'user'}>{'User'}</label> <input type={'text'} id={'user'} /> -
How to combine multiple inline style objects?
You can use spread operator in regular React:
<button style={{...styles.panel.button, ...styles.panel.submitButton}}>{'Submit'}</button>If you're using React Native then you can use the array notation:
<button style={[styles.panel.button, styles.panel.submitButton]}>{'Submit'}</button> -
How to re-render the view when the browser is resized?
You can listen to the
resizeevent incomponentDidMount()and then update the dimensions (widthandheight). You should remove the listener incomponentWillUnmount()method.class WindowDimensions extends React.Component { constructor(props){ super(props); this.updateDimensions = this.updateDimensions.bind(this); } componentWillMount() { this.updateDimensions() } componentDidMount() { window.addEventListener('resize', this.updateDimensions) } componentWillUnmount() { window.removeEventListener('resize', this.updateDimensions) } updateDimensions() { this.setState({width: window.innerWidth, height: window.innerHeight}) } render() { return <span>{this.state.width} x {this.state.height}</span> } }