Member-only story
React Tips — Titles, Default Props, and Hooks with Function Components
4 min readSep 15, 2020
React is a popular library for creating web apps and mobile apps.
In this article, we’ll look at some tips for writing better React apps.
Render New React Component on Click
We can render a new React component on click if we set a state so that the component can be rendered.
For example, we can write:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
showComponent: false,
};
this.onClick= this.onClick.bind(this);
} onClick() {
this.setState({
showComponent: true,
});
} render() {
return (
<div>
<button onClick={this.onClick}>click me</button>
{this.state.showComponent ?
<Foo /> :
null
}
</div>
);
}
}
We have a button that runs the this.onClick
method on click.
It changes the showComponent
state to true
.
Then we can make the Foo
component show when this.state.showComponent
is true
.