All the fundamental React.js concepts, jammed into this single Medium article


Fundamental #1: React is all about components

// Example 1
// https://jscomplete.com/repl?j=Sy3QAdKHWfunction Button (props) {
  // Returns a DOM element here. For example:
  return <button type="submit">{props.label}</button>;
}// To render the Button component to the browser
ReactDOM.render(<Button label="Save" />, mountNode)

Fundamental #2: What the flux is JSX?

// Example 2 -  React component without JSX
// https://jscomplete.com/repl?j=HyiEwoYB-function Button (props) {
  return React.createElement(
    "button",
    { type: "submit" },
    props.label
  );
}// To use Button, you would do something like
ReactDOM.render(
  React.createElement(Button, { label: "Save" }),
  mountNode
);
// Example 3 -  React’s createElement API
// https://jscomplete.com/repl?j=r1GNoiFBbconst InputForm = React.createElement(
  "form",
  { target: "_blank", action: "https://google.com/search" },
  React.createElement("div", null, "Enter input and click Search"),
  React.createElement("input", { name: "q", className: "input" }),
  React.createElement(Button, { label: "Search" })
);// InputForm uses the Button component, so we need that too:
function Button (props) {
  return React.createElement(
    "button",
    { type: "submit" },
    props.label
  );
}// Then we can use InputForm directly with .render
ReactDOM.render(InputForm, mountNode);
// Example 4 - JSX (compare with Example 3)
// https://jscomplete.com/repl?j=SJWy3otHWconst InputForm =
  <form target="_blank" action="https://google.com/search">
    <div>Enter input and click Search</div>
    <input name="q" className="input" />
    <Button label="Search" />
  </form>;// InputForm "still" uses the Button component, so we need that too.
// Either JSX or normal form would do
function Button (props) {
  // Returns a DOM element here. For example:
  return <button type="submit">{props.label}</button>;
}// Then we can use InputForm directly with .render
ReactDOM.render(InputForm, mountNode);

Fundamental #3: You can use JavaScript expressions anywhere in JSX

// Example 5 -  Using JavaScript expressions in JSX
// https://jscomplete.com/repl?j=SkNN3oYSWconst RandomValue = () => 
  <div>
    { Math.floor(Math.random() * 100) }
  </div>;// To use it:
ReactDOM.render(<RandomValue />, mountNode);
// Example 6 - An object passed to the special React style prop
// https://jscomplete.com/repl?j=S1Kw2sFHbconst ErrorDisplay = ({message}) =>
  <div style={ { color: 'red', backgroundColor: 'yellow' } }>
    {message}
  </div>;// Use it:
ReactDOM.render(
  <ErrorDisplay 
    message="These aren't the droids you're looking for" 
  />,
  mountNode
);
// Example 7 - Using a React element within {}
// https://jscomplete.com/repl?j=SkTLpjYr-const MaybeError = ({errorMessage}) =>
  <div>
    {errorMessage && <ErrorDisplay message={errorMessage} />}
  </div>;
  
// The MaybeError component uses the ErrorDisplay component:
const ErrorDisplay = ({message}) =>
  <div style={ { color: 'red', backgroundColor: 'yellow' } }>
    {message}
  </div>;// Now we can use the MaybeError component:
ReactDOM.render(
  <MaybeError
    errorMessage={Math.random() > 0.5 ? 'Not good' : ''}
  />,
  mountNode
);
// Example 8 - Using an array map inside {}
// https://jscomplete.com/repl?j=SJ29aiYH-const Doubler = ({value=[1, 2, 3]}) =>
  <div>
    {value.map(e => e * 2)}
  </div>;// Use it
ReactDOM.render(<Doubler />, mountNode);

Fundamental #4: You can write React components with JavaScript classes

// Example 9 - Creating components using JavaScript classes
// https://jscomplete.com/repl?j=ryjk0iKHbclass Button extends React.Component {
  render() {
    return <button>{this.props.label}</button>;
  }
}// Use it (same syntax)
ReactDOM.render(<Button label="Save" />, mountNode);
// Example 10 -  Customizing a component instance
// https://jscomplete.com/repl?j=rko7RsKS-class Button extends React.Component {
  constructor(props) {
    super(props);
    this.id = Date.now();
  }
  render() {
    return <button id={this.id}>{this.props.label}</button>;
  }
}// Use it
ReactDOM.render(<Button label="Save" />, mountNode);
// Example 11 — Using class properties
// https://jscomplete.com/repl?j=H1YDCoFSbclass Button extends React.Component {
  clickCounter = 0;  handleClick = () => {
    console.log(`Clicked: ${++this.clickCounter}`);
  };
  
  render() {
    return (
      <button id={this.id} onClick={this.handleClick}>
        {this.props.label}
      </button>
    );
  }
}// Use it
ReactDOM.render(<Button label="Save" />, mountNode);
// Wrong:
onClick={this.handleClick()}// Right:
onClick={this.handleClick}

Fundamental #5: Events in React: Two Important Differences

// Example 12 - Working with wrapped events
// https://jscomplete.com/repl?j=HkIhRoKBbclass Form extends React.Component {
  handleSubmit = (event) => {
    event.preventDefault();
    console.log('Form submitted');
  };
  
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <button type="submit">Submit</button>
      </form>
    );
  }
}// Use it
ReactDOM.render(<Form />, mountNode);

Fundamental #6: Every React component has a story

Fundamental #7: React components can have a private state

// Example 13 -  the setState API
// https://jscomplete.com/repl?j=H1fek2KH-class CounterButton extends React.Component {
  state = {
    clickCounter: 0,
    currentTimestamp: new Date(),
  };
  
  handleClick = () => {
    this.setState((prevState) => {
     return { clickCounter: prevState.clickCounter + 1 };
    });
  };
  
  componentDidMount() {
   setInterval(() => {
     this.setState({ currentTimestamp: new Date() })
    }, 1000);
  }
  
  render() {
    return (
      <div>
        <button onClick={this.handleClick}>Click</button>
        <p>Clicked: {this.state.clickCounter}</p>
        <p>Time: {this.state.currentTimestamp.toLocaleString()}</p>
      </div>
    );
  }
}// Use it
ReactDOM.render(<CounterButton />, mountNode);

Fundamental #8: React will react

Fundamental #9: React is your agent

Fundamental #10: Every React component has a story (part 2)


jsComplete EdgeCoders

We write about the new and leading edge technologies with a focus on JavaScript

Samer Buna

Written by

Author for Pluralsight, O'Reilly, Manning, and LinkedIn Learning. Curator of jsComplete.com

jsComplete EdgeCoders

We write about the new and leading edge technologies with a focus on JavaScript