Create new component in React
// CREATE CLASS NAMED AS COMPOENT NAME
class ComponentName extends React.Component {
constructor(props) {
super(props);
this.state = {
prop_name: 'value',
prop_name2: `Hello ${this.props.name}, `
}
this.onChange = this.onChange.bind(this); //IF YOU WANT TO USE 'this' KEYWORD
}
onChange(e) {
this.setState({
prop_name: e.target.value
})
}
render() {
return (
<div>
<p className="sample_class">{ this.state.prop_name }</p>
<input className="input_ctrl" name="name" placeholder="Enter text" onChange={this.onChange} />
</div>
)
}
}
ReactDOM.render(<ComponentName name="Your name" />, document.getElementById('app'));
The code shows you how to create a new component in React. First, we create a class which has the name as our component name and initialize its constructor. The constructor will be called when the component is called and we can get passed properties here. We can also assign values to our state properties in the constructor.Â
If you want to use this keyword in this constructor you have to bind a function to its onChange property as in the code snippet. Here we have assigned the 'onChange' method in the constructor so we have to create it inside our class.
The render function will return the HTML that we want to render on the page. If you want to use this component you can call it using 'ReactDOM.render' where 'app' is the id of the element inside which we want to render our component.