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()}>❮</button>
<button class="next" onClick={() => this.slideTransitionNext()}>❯</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>