Categories
React Answers

How to pass text between React component tags?

Sometimes, we want to pass text between React component tags.

In this article, we’ll look at how to pass text between React component tags.

How to pass text between React component tags?

To pass text between React component tags, we can add the children prop as a prop of the component we want to put text in between the tags of.

For instance, we write:

import React from "react";

const Foo = ({ children }) => <h1>{children}</h1>;

export default function App() {
  return <Foo>hello world</Foo>;
}

We create the Foo component that takes the children prop.

And we render children in between the h1 tags.

Next, we put ‘hello world’ in between the opening and closing Foo tags in App.

As a result, we should ‘hello world’ rendered between the h1 tags and we see it rendered in bold.

Conclusion

To pass text between React component tags, we can add the children prop as a prop of the component we want to put text in between the tags of.

Categories
React Answers

How to add scroll event listeners in a React component?

Sometimes, we want to add scroll event listeners in a React component.

In this article, we’ll look at how to add scroll event listeners in a React component.

How to add scroll event listeners in a React component?

To add scroll event listeners in a React component, we can set the onScroll prop of an element to an event handler function.

For instance, we write:

import React from "react";

export default function App() {
  const onScroll = (e) => console.log(e);

  return (
    <div onScroll={onScroll} style={{ height: 50, overflowY: "scroll" }}>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed lobortis,
      elit at varius euismod, felis felis scelerisque lacus, at laoreet neque
      nisi sit amet arcu. Nullam placerat porttitor justo, non pretium justo
      fringilla aliquam. Vivamus vel odio imperdiet nisi faucibus hendrerit.
      Nunc finibus nisi faucibus nulla ultrices, nec consequat tellus
      condimentum. Cras et pulvinar augue. Aliquam laoreet dolor ultrices mi
      laoreet, in laoreet enim venenatis. Sed faucibus ipsum nec quam iaculis,
    </div>
  );
}

We create the onScroll function that logs the scroll event object.

Then we assign the onScroll function as the value of the onScroll prop of the div.

Now when we scroll up and down, we should see the scroll event object logged.

Conclusion

To add scroll event listeners in a React component, we can set the onScroll prop of an element to an event handler function.

Categories
React Answers

How to switch between pages in React?

Sometimes, we want to switch between pages in React.

In this article, we’ll look at how to switch between pages in React.

How to switch between pages in React?

To switch between pages in React, we can use the React Router package.

To install it, we run:

npm i react-router

Then to use it, we write:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  NavLink
} from "react-router-dom";

const Foo = () => {
  return <p>foo</p>;
};

const Bar = () => {
  return <p>bar</p>;
};

export default function App() {
  return (
    <Router>
      <style>{`.is-active { font-weight: bold }`}</style>
      <div>
        <ul>
          <li>
            <NavLink to="/foo" activeClassName="is-active">
              foo
            </NavLink>
          </li>
          <li>
            <NavLink to="/bar" activeClassName="is-active">
              bar
            </NavLink>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

First, we create the Foo and Bar page components.

Next, we add the Routes to map the URLs to the components to render.

Then we add the NavLinks to add links that lets us set the class name of the active link.

We set activeClassName to a string for the class name of the active link.

In the style element, we add a string to style anything with the is-active class by making the font bold.

Therefore, when we click on the links, we’ll see the link for the current page bolded.

Conclusion

To switch between pages in React, we can use the React Router package.

Categories
React Answers

How to style react-datepicker?

Sometimes, we want to style react-datepicker.

In this article, we’ll look at how to style react-datepicker.

How to style react-datepicker?

To style react-datepicker, we can set the wrapperClassName prop to a class name.

And then we can apply styles to that class name.

For instance, we write:

import React from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";

export default function App() {
  return (
    <div>
      <style>
        {`.date-picker input {
          width: 100%
      }`}
      </style>
      <DatePicker wrapperClassName="date-picker" />
    </div>
  );
}

We set wrapperClassName to 'date-picker'.

And then we add some styles to the class in the style element.

We set the width of the input to 100%, so it’ll fill the whole container.

As a result, we should see the date picker input fill the whole container.

Conclusion

To style react-datepicker, we can set the wrapperClassName prop to a class name.

And then we can apply styles to that class name.

Categories
React Answers

How to update a state when state is an array of objects with React?

Sometimes, we want to update a state when state is an array of objects with React.

In this article, we’ll look at how to update a state when state is an array of objects with React.

How to update a state when state is an array of objects with React?

To update a state when state is an array of objects with React, we can return a new array with the values we want in the state setter function’s callback.

For instance, we write:

import React, { useState } from "react";

const items = [
  { id: 1, num: 1 },
  { id: 2, num: 2 },
  { id: 3, num: 3 }
];

export default function App() {
  const [vals, setVals] = useState(items);
  const onClick = () => {
    setVals((vals) => {
      return [
        ...vals.slice(0, 1),
        { id: 2, num: Math.random() * 100 },
        ...vals.slice(2)
      ];
    });
  };

  return (
    <div>
      <button onClick={onClick}>update</button>
      {vals.map((v) => {
        return <p key={v.id}>{v.num}</p>;
      })}
    </div>
  );
}

We define the vals state with the useState hook.

Then we define the onClick function that calls setVals with a callback that takes the existing vals array value as the parameter.

And then we return the new value for the vals state by updating the 2nd entry of it and keeping the rest the same.

We spread the existing elements returned by slice and only change the num property of the 2nd entry.

Finally, we set the onClick prop of the button to onClick so vals is updated when we click it.

And we render the num in vals with vals.map.

Conclusion

To update a state when state is an array of objects with React, we can return a new array with the values we want in the state setter function’s callback.