0

I'm trying to make a webpage and I want to condense some of the HTML and respective code into a react components, but I can't seem to do this without creating an entire react app, which is undesired for this project. I have followed the steps in the react documentation to add a JSX preprocessor and then render the react component into the page using script tag, but nothing shows up.

In the console in the page, it just says Uncaught ReferenceError: require is not defined. I tried using browserify to compile all of the react libraries to one file, but it said Error: Can't walk dependency graph: Cannot find module 'reactjs' from '/home/user/code/website/src/slideshow.js'. If I try and npm install reactjs it installs react, and neither give any definitions or descriptions for the react classes when editing the code.

I'm kind of lost, and completely willing to look like an idiot. My HTML and JS is below.

const { React, ReactDOM } = require('react');
const root = ReactDOM.createRoot(document.getElementById("slideshowContainer"));

class Slideshow extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            slide: 1,
        }
        this.slides = {
            1: {
                src: './assets/coding.jpeg',
                caption: "this is slide 1."
            },
            2: {
                src: './assets/coding2.jpeg',
                caption: "this is slide 2."
            },
            3: {
                src: './assets/templimg.jpg',
                caption: "this is slide 3."
            }
        }
    }

    slideTransitionPrev() {
        let ok = Object.keys(this.slides);

        if (this.state.slide === 1) {
            this.setState({ slide: ok });
        } else {
            this.setState({ slide: this.state.slide - 1 });
        }
    }

    slideTransitionNext() {
        let ok = Object.keys(this.slides);

        if (this.state.slide === ok) {
            this.setState({ slide: 1 });
        } else {
            this.setState({ slide: this.state.slide + 1 });
        }
    }

    render() {
        return (
            <div class="slides fade">
                <span class="slidePosition">{this.state.slide} / {Object.keys(this.slides)}</span>
                <img style="width: 100%" src={this.slides[this.state.slide].src} />

                <button class="prev" onClick={() => this.slideTransitionPrev()}>&#10094;</button>
                <button class="next" onClick={() => this.slideTransitionNext()}>&#10095;</button>

                <span class="caption">{this.slides[this.state.slide].caption}</span>
            </div>
        )
    }
}

root.render(<Slideshow />);
(boring necessary html stuff)

<body>
    <div id="slideshowContainer"></div>

    <script src="./src/slideshow.js"></script>
</body>

2 Answers2

0

The client's browser must ultimately consume plain JavaScript. JSX is not plain JavaScript. You need to decide whether you want to compile the JSX into JavaScript on your end (as the developer) or the client's.

For anything remotely professional, you should do so on your end; doing so on the client puts a good amount of load onto the client's device which may not work well for some, like with lower-end phones. Processing the JSX into JS yourself also allows for many other nice enhancements. I think it's really worth it for anything outside of small toy snippets. An often-used tool for this is create-react-app.

If you really don't want to use that route, you can use Babel Standalone to turn JSX into JS on the client, like this:

<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
const App = () => {
    return 'foo';
};

ReactDOM.createRoot(document.querySelector('.react')).render(<App />);
</script>

You'll need to include React, React DOM, Babel, and lastly your own script (in a <script type="text/babel"> tag).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • So I don't think I clarified it enough but I did follow some steps on the react website to have babel convert the JSX into JS. So I have a different JS file than what i mentioned in my post. I don't want to use create-react-app though. Is there a way I can have this work using a node backend? Otherwise, is the only way to include js libraries in an HTML page through extra script tags? – imacrazyguylol Nov 16 '22 at 02:47
  • You don't have to use create-react-app, but you *do* need to use a transpiler (Babel) somewhere - either on the frontend (with Babel Standalone) or on the backend (on your server or dev machine). – CertainPerformance Nov 16 '22 at 04:12
  • Yeah I’m saying that I have done that – imacrazyguylol Nov 16 '22 at 13:30
  • Which one have you done, and what problems are you having with it? – CertainPerformance Nov 16 '22 at 13:41
  • I followed what the react docs said, I used npx babel —watch which supposedly creates preprocessed JS from JSX. The problem I’m having is that it doesn’t register the react library. It says that require doesn’t work, so I tried browserify to compile the library into the JS, but then it told me that I didn’t have react. – imacrazyguylol Nov 16 '22 at 14:55
  • If you're doing it manually, it requires a moderate amount of setup. If you aren't good at that, why not just use create-react-app and let it manage it for you? The end result is the same, and everything you'd want to configure is still available as an option – CertainPerformance Nov 16 '22 at 14:56
  • I'm working with someone else on this project who is unfamiliar with react, and afaik create-react-app doesn't integrate with regular HTML. – imacrazyguylol Nov 16 '22 at 15:02
  • It can. Just give it a target element to populate when calling `.render`, while the rest of the HTML outside of that element will be left alone (and could have, for example, vanilla DOM methods attached to events, and jQuery, and whatever else you'd want) – CertainPerformance Nov 16 '22 at 15:09
0

npm is used for node js. You can't import those libraries to a normal html/js file. On this page there are reference links to the javascript files you need: https://reactjs.org/docs/add-react-to-a-website.html