How to avoiding “options” props from being initialised inline?

Asked
Active3 hr before
Viewed126 times

9 Answers

optionsprops
90%

If I start combat by making an attack, does a high-initiative enemy see it coming? , Stack Overflow Public questions & answers , How is a crossword clue to be interpreted when it contains (… includes part of #-Direction)?

You could use useMemo for this

const ParentComp = ({ uri, someOtherProp }) => {
  const options = React.useMemo(() => ({ uri }), [uri]);
  return (
    <SubComp
      options={options}
      someOtherProp={someOtherProp}
    />
  );
};

If you have lots of props and just want SubComponent to re render when something changes you can do the following:

const ParentComp = ({ uri, someOtherProp }) => {
  const memoProps = React.useMemo(
    () => ({
      options: { uri },
      someOtherProp,
    }),
    [someOtherProp, uri]
  );
  return <SubComp {...memoProps} />;
};
load more v
88%

When using memoization, remember a couple of constraints:,In real world applications, components often contain a mix of controlled and uncontrolled behaviors. This is okay! If each value has a clear source of truth, you can avoid the anti-patterns mentioned above.,Continuing the example above, we could avoid accidentally erasing state by only updating it when props.email changes:

class EmailInput extends Component {
  state = { email: this.props.email };

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }

  handleChange = event => {
    this.setState({ email: event.target.value });
  };

  componentWillReceiveProps(nextProps) {
    // This will erase any local state updates!
    // Do not do this.
    this.setState({ email: nextProps.email });
  }
}
load more v
72%

Props can be used to style styled components in the same way that they are passed to normal React components. Props are used instead of classes in CSS and set the properties dynamically.,Next, we’ll look at two libraries that can be used to implement this in a React app.,There seems to be a number of ways of styling React components used widely in the industry for production level work:

Pretag
 Pretag team - issue, fix, solve, resolve
65%

Specify editor & plugin versions ,Additional settings passed to the tinymce.init({...}) method used to initialize the editor., Spell Checker plugin

 $ npx create - react - app tinymce - react - demo
load more v
75%

string | control prop (read more about this in the Control Props section),These are functions you can call to change the state of the downshift component.,Children Function prop getters actions state props

* docs: update README.md[skip ci]

   *
   docs: update.all - contributorsrc[skip ci]

Co - authored - by: allcontributors[bot] < 46447321 + allcontributors[bot] @users.noreply.github.com >
load more v
40%

<Create> also accepts a record prop, to initialize the form based on a value object.,Some form layouts also use Card, in which case the user ends up seeing a card inside a card, which is bad UI. To avoid that, you can override the main page container by passing a component prop :,You can override this behavior and pass custom side effects by providing a function as onFailure prop:

<Resource name="posts" create={PostCreate} edit={PostEdit} />
                               ----------        --------
                                    |               |
    displayed when browsing to /posts/create        |
                                                    |
                    displayed when browsing to /posts/123
load more v
22%

Another example, when returning an object, remember to wrap the curly brackets in parentheses to avoid it being considered the wrapping function body brackets:,create-react-app is a project aimed at getting you up to speed with React in no time, and any React app that needs to outgrow a single page will find that create-react-app meets that need.,npm eject: to eject from create-react-app

Pretag
 Pretag team - issue, fix, solve, resolve
60%

Pretag
 Pretag team - issue, fix, solve, resolve
48%

But now route props are not being passed implicitly, so how do we access match, history or location? Do we have to wrap all components with withRouter? That is where the hooks steps in.,When using the component syntax, route props (match, location and history) are implicitly being passed on to the component. But it has to be changed to render once you have extra props to pass to the component. Note that adding an inline function to the component syntax would lead to the component re-mounting on every render.,Note that hooks were introduced in 16.8 version of React, so you need to be above that version to use them.

// When you wanted to render the route and get router props for component
<Route path="/" component={Home} />


// Or when you wanted to pass extra props
<Route path="/" render={({ match }) => <Profile match={match} mine={true} />}>
<Route path="/">
   <Home />
</Route>
import { useHistory } from 'react-router-dom';

function Home() {
  const history = useHistory();
  return <button onClick={() => history.push('/profile')}>Profile</button>;
}
import { useLocation } from 'react-router-dom';

function Profile() {
  const location = useLocation();
  useEffect(() => {
    const currentPath = location.pathname;
    const searchParams = new URLSearchParams(location.search);
  }, [location]);
  return <p>Profile</p>;
}
import { useParams, Route } from 'react-router-dom';

function Profile() {
  const { name } = useParams();
  return <p>{name}'s Profile</p>;
}

function Dashboard() {
  return (
    <>
      <nav>
        <Link to={`/profile/ann`}>Ann's Profile</Link>
      </nav>
      <main>
        <Route path="/profile/:name">
          <Profile />
        </Route>
      </main>
    </>
  );
}
import { useRouteMatch, Route } from 'react-router-dom';

function Auth() {
  const match = useRouteMatch();
  return (
    <>
      <Route path={`${match.url}/login`}>
        <Login />
      </Route>
      <Route path={`${match.url}/register`}>
        <Register />
      </Route>
    </>
  );
}

For example, consider that you need your own profile to be rendered at /profile and somebody else’s profile if the URL contains the name of the person /profile/dan or /profile/ann. Without using the hook, you would either write a Switch, list both routes and customize them with props. But now, using the hook we can do this:

import {
  Route,
  BrowserRouter as Router,
  Link,
  useRouteMatch,
} from 'react-router-dom';

function Profile() {
  const match = useRouteMatch('/profile/:name');

  return match ? <p>{match.params.name}'s Profile</p> : <p>My own profile</p>;
}

export default function App() {
  return (
    <Router>
      <nav>
        <Link to="/profile">My Profile</Link>
        <br />
        <Link to={`/profile/ann`}>Ann's Profile</Link>
      </nav>
      <Route path="/profile">
        <Profile />
      </Route>
    </Router>
  );
}
load more v

Other "options-props" queries related to "How to avoiding “options” props from being initialised inline?"