Skip to content

Props Tutorial

kmoran04 edited this page Oct 27, 2019 · 9 revisions

Props are the inputs to components, which are like JavaScript functions. These components accept props and return React elements describing what should appear on the screen. Props are a way to pass read-only data from a parent to a child component. If you are trying to change a prop from within the component, that usually means it should be managed by state instead.

State on the other hand is also variables like props, but directly initialized and managed by the component.

If our counter button were to be static, with a value of 5 for example, we could reference it using something like:

class Counter extends Component {
  render() {
    return <button>{this.props.count}</button>;
  }
}

//And then in App.tsx, we would pass in the value of 5 using:

<Counter count={5}/>

//However, we use state to make the button dynamic and replace the this.props.count with useState:

const Hello: React.FC = () => {
  const [counter, setCounter] = useState(0);

  return (
    <div>
      <p>Hello, world!</p>
      <p>You clicked {counter} times</p>
      <button onClick={() => setCounter(counter + 1)}>Click me</button>
    </div>
  );
};
export default Hello;

In TypeScript, all objects have types. In order to pass properties to your React component, the properties it is expecting should be defined in a type, usually named in the style of ComponentNameProps. This acts like a struct, like below:

type SearchBarProps {
   placeholderText: string;
}

const SearchBar: React.FC<SearchBarProps> = (props) => {
    // we can now access props.placeholderText in the component
}