Categories
React Answers

How to Add the CSS display: none Style within a Conditional Expression with React?

Sometimes, we want to add the CSS display: none style within a conditional expression with React.

In this article, we’ll look at how to add the CSS display: none style within a conditional expression with React.

Add the CSS display: none Style within a Conditional Expression with React

To add the CSS display: none style within a conditional expression with React, we can pass in an object into the style prop of an element.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [show, setShow] = useState(true);
  return (
    <div>
      <button onClick={() => setShow((s) => !s)}>toggle</button>
      <div style={{ display: show ? "block" : "none" }}>hello</div>
    </div>
  );
}

We have the show state that we create with the useState hook.

Then we set the onClick prop of the button to a function that calls setShow to toggle show between true and false .

And then we can set the display CSS property of the div with a ternary expression.

If show is true , then set it to 'block' .

Otherwise, we set it to 'none' .

Conclusion

To add the CSS display: none style within a conditional expression with React, we can pass in an object into the style prop of an element.

Categories
React Answers

How to Render Markdown in a React Component?

Sometimes, we want to render Markdown in a React component.

In this article, we’ll look at how to render Markdown in a React component.

Render Markdown in a React Component

To render Markdown in a React component, we can use the react-markdown library.

To install it, we run:

npm i react-markdown

Then we can render a Markdown string by writing:

import React from "react";
import ReactMarkdown from "react-markdown";
const gfm = require("remark-gfm");
const markdown = `Just a link: https://reactjs.com.`;

export default function App() {
  return <ReactMarkdown remarkPlugins={[gfm]} children={markdown} />;
}

We use the ReactMarkdown component with the children prop set to the string with the Markdown content.

The remarkPlugins prop is set to an array with the gfm plugin for parsing Remark Markdown.

Conclusion

To render Markdown in a React component, we can use the react-markdown library.

Categories
React Answers

How to Iterate Through a Hash and Return JSX Elements for Each Key with React?

Sometimes, we want to iterate through a hash and return JSX elements for each key with React.

In this article, we’ll look at how to iterate through a hash and return JSX elements for each key with React.

Iterate Through a Hash and Return JSX Elements for Each Key with React

To iterate through a hash and return JSX elements for each key with React, we can use the Object.keys method to get an array with the object property name strings.

Then we can call map to map them to the elements we want.

For instance, we can write:

import React from "react";

const obj = {
  foo: 1,
  bar: 2,
  baz: 3
};

export default function App() {
  return (
    <div>
      {Object.keys(obj).map((k) => (
        <p key={k}>{k}</p>
      ))}
    </div>
  );
}

to get all the keys of obj with Object.keys .

Then we call map with a callback to return p elements with the key name k as its content.

We should set the key prop to a unique value so that React can key track of the items.

Therefore, now we get:

foo

bar

baz

on the screen.

Conclusion

To iterate through a hash and return JSX elements for each key with React, we can use the Object.keys method to get an array with the object property name strings.

Then we can call map to map them to the elements we want.

Categories
React Answers

How to Generate a PDF File from React Components?

Sometimes, we want to generate a PDF file from React components.

In this article, we’ll look at how to generate a PDF file from React components.

Generate a PDF File from React Components

To generate a PDF file from React components, we can use the js-pdf and react-dom/server libraries.

To install js-pdf , we run:

npm i js-pdf

react-dom/server comes with projects created by Create React App by default.

To use it, we write:

import React from "react";
import ReactDOMServer from "react-dom/server";
import jsPDF from "jspdf";
const doc = new jsPDF();
const Foo = <b>foo</b>;

export default function App() {
  const save = () => {
    doc.html(ReactDOMServer.renderToStaticMarkup(Foo), {
      callback: () => {
        doc.save("myDocument.pdf");
      }
    });
  };

  return (
    <div>
      <button onClick={save}>save</button>
    </div>
  );
}

We create a new instance of the jsPDF constructor and assign it to doc .

Then we have the Foo JSX expression which renders some bold text.

Next, in App , we create the save function that calls the doc.html method with the HTML string created by renderToStaticMarkup method.

And then we set the callback property to a function that calls docs.save with the file name to save the rendered HTML version of Foo as a PDF.

Conclusion

To generate a PDF file from React components, we can use the js-pdf and react-dom/server libraries.

Categories
React Answers

How to Play Sound in React?

Sometimes, we want to play sound in React.

In this article, we’ll look at how to play sound in React.

Play Sound in React

To play sound in React, we can use the Audio constructor to create an audio element to play the clip.

Then we can control it with JavaScript.

For instance, we can write:

import React, { useEffect, useState } from "react";

const useAudio = (url) => {
  const  = useState(new Audio(url));
  const [playing, setPlaying] = useState(false);

const toggle = () => setPlaying(!playing);

  useEffect(() => {
    playing ? audio.play() : audio.pause();
  }, [playing, audio]);

  useEffect(() => {
    audio.addEventListener("ended", () => setPlaying(false));
    return () => {
      audio.removeEventListener("ended", () => setPlaying(false));
    };
  }, );

  return [playing, toggle];
};

export default function App() {
  const [playing, toggle] = useAudio(
    "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
  );

  return (
    <div>
      <button onClick={toggle}>{playing ? "Pause" : "Play"}</button>
    </div>
  );
}

We create the useAudio hook that takes the url of the clip that we want to play.

Then we create the audio state that’s set to the audio element that’s created with the Audio constructor with the url of the clip.

Then we create the playing state which keeps track of whether the audio clip is playing.

Next, we call the useEffect hook to call audio.play or audio.pause depending if playing is true or not.

After that, we call useEffect again with a callback to listen to the ended event and call setPlaying with false to set playing to false in either case.

Finally, we return playing and toggle so we can use them in a component.

In App , we call useAudio with the URL of the clip we want to play.

And then we set toggle as the value of onClick and display ‘Pause’ or ‘Play’ depending on the value of playing .

Now when we click on the button, the clip should play if it’s not playing and pause it otherwise.

Conclusion

To play sound in React, we can use the Audio constructor to create an audio element to play the clip.

Then we can control it with JavaScript.