Refs
import React, { Fragment, Component } from 'react'; import { getFunName } from '../helpers'; class StorePicker extends Component { constructor() { super(); //use this to create the component before we start changing it console.log( "Gonna create a component!"); this.goToStore = this.goToStore.bind( this ); //doing this allows the keyword ''this'' to be used in the function it is being executed from } handleClick() { //alert( 'Hey!' ); } myInput = React.createRef(); goToStore( event ) { //1. Stop the form from submitting event.preventDefault(); //2. get the text from that input console.log( this ); //not the keyword this works because of the binding //3. Change the page to /store/whatever-they-entered } render() { return ( <Fragment> <form action ="" className="store-selector" onSubmit={ this.goToStore }> <h2>Please enter a store</h2> <input type="text" ref={ this.myInput } placeholder="store name" required defaultValue={ getFunName() } /> <button onClick={ this.handleClick } type="submit" className="btn" > visit store </button> </form> </Fragment> ) } } export default StorePicker;
- grabbing the data using a ref
import React, { Fragment, Component } from 'react'; import { getFunName } from '../helpers'; class StorePicker extends Component { handleClick() { //alert( 'Hey!' ); } myInput = React.createRef(); goToStore = ( event ) => { //1. Stop the form from submitting event.preventDefault(); //2. get the text from that input console.log( this.myInput ); //3. Change the page to /store/whatever-they-entered } render() { return ( <Fragment> <form action ="" className="store-selector" onSubmit={ this.goToStore }> <h2>Please enter a store</h2> <input type="text" ref={ this.myInput } placeholder="store name" required defaultValue={ getFunName() } /> <button onClick={ this.handleClick } type="submit" className="btn" > visit store </button> </form> </Fragment> ) } } export default StorePicker;
- this is also equivalent