Setting HTML in a data attribute in Reactjs - javascript

I can not figure it out that how is it possible to use HTML in a data attribute inside React's jsx.
Like
data-bs-template='<div class="tooltip d-none d-md-block" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'
Is this approach right or wrong?

In order set HTML in a React component, you need to create an object that has the __html property and the a string that contains the relevant HTML markup. Like this:
{__html: '<span>Something</span>'};
And finally render it using dangerouslySetInnerHTML which is React's replacement for the native innerHTML:
function Tooltip(props) {
const someHTML = {
__html: `<div class="tooltip d-none d-md-block" role="tooltip"><div class="arrow"></div><div class="tooltip-inner">${props.text}</div></div>`
};
return <div dangerouslySetInnerHTML={someHTML}></div>;
}
function App() {
return (
<div className="container">
<Tooltip text="Hello this is a tooltip" />
</div>
);
}
ReactDOM.render( < App / > , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

You just pass attribute like this:
data-bs-template={
"<div class="tooltip d-none d-md-block" role="tooltip">
<div class="arrow"></div>
<div class="tooltip-inner"></div>
</div>"
}
Updated Code

There is your answer:
const App = () => {
const data = '<b>lorem ipsum</b>';
return (
<div
dangerouslySetInnerHTML={{__html: data}}
/>
);
}
export default App;

Related

how to use background image using props using reactjs

here is my code where i'm trying to pass object like{title,description,backgroundImg ....} to section component using props , I am getting all the key & value but when I use it on section component getting all data value instead of backgroundImg why..?
import React from "react";
import Section from "./Section";
function Home() {
return (
<div>
<div className="container">
<Section
title="Model S"
description="Order Online for Touchless Delivery"
backgroundImg="model-s.jpg"
leftButton="custom order"
rightButton="existing inventory"
/>
<Section
title="Model Y"
description="Order Online for Touchless Delivery"
backgroundImg="../images/model-y.jpg"
leftButton="custom order"
rightButton="existing inventory"
/>
</div>
);
}
export default Home;
to
import React from "react";
import DownArrow from "../images/down-arrow.svg";
const Section = (props) => {
return (
<div
className="Wrap"
style={{ backgroundImage: `url(${props.backgroundImg})` }}
>
<div className="item_text">
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
<div className="">
<div className="item_buttom">
<div className="leftButton">{props.leftButton}</div>
<div className="RightButton">{props.rightButton}</div>
</div>
<div>
<img src={DownArrow} alt="svgImg" className="DownArrow" />
</div>
</div>
</div>
);
};
export default Section;
My image folder path is "../images/..."
You need to import image in your home component.
Like
import sectionImage from "../images/image.jpg";
then pass the image like
<Section
backgroundImg={sectionImage}
/>
Then it should work fine.

Having trouble rendering an array of images from an api (Django Rest Framework) response in React

Hi this is my first project in both React and Django Rest Framework and I need to figure this out to complete the project.
The issue I'm having (I believe it's a React one) is that my api is returning an json response which React receives using axios which works fine since when I do the console log all the data is there and Im also able to pass the data to a tag, etc. I would like to display the photos that are being sent to by the api. The link is not the problem as I am able to view the photo in the browser using the link provided by the api. The problem is that I have multiple images in the api response that are set up as an array.
As shown here:
postmanResponse
Response using console:
enter image description here
I guess essentially what I'm asking is there a way that I can make an array/object with the image array that my api is delivering so that I can then use it to show the picture in React?
Any help will be helpful. Thank you!
Here is my code for the React side:
// Import Files
import React, { Component } from 'react';
// Import Axios
import axios from "axios";
// Import Is Mobile
import { isMobile } from 'react-device-detect';
// Import Css
import "./projectDetail.css";
// Mobile Css
import "./projectDetailM.css"
// Lightbox
import { SRLWrapper } from "simple-react-lightbox";
// Import Footer
import Footer from "../Footer/footer"
// Project Detail Class
class ProjectDetail extends Component {
// States
state = {
data: [],
photoIndex: 0,
isOpen: false,
}
// Mount Data to the State
componentDidMount() {
this.handleFetchItem();
}
// Get the project via axios
handleFetchItem = () => {
// Variables
const {
match: { params }
} = this.props
// Set State
this.setState({ loading: true });
// Axios Setup
axios.get('http://127.0.0.1:8000/projects/' + params.ID)
.then(res => {
this.setState({ data: res.data, loading: false });
})
.catch(console.error());
}
// Render the page
render() {
// Const
const { data } = this.state;
const project = data;
// Print to console (Debugging)
//console.log(data);
// Return Page
return (
<div className="projectDetailMainContainer">
<div className="projectDetailGrid">
<div className="projectDetailArea">
<div className="projectNameArea">
<h1 className="projectNameStyling">
{project.title}
</h1>
</div>
<div className="projectAddress1Area">
<h2 className="projectAddress1Styling">
{project.address},
</h2>
</div>
<div className="projectAddress2Area">
<h2 className="projectAddress2Styling">
{project.address2}
</h2>
</div>
<div className="projectCityArea">
<h2 className="projectCityStyling">
{project.city} {project.zipcode}
</h2>
</div>
<div className="projectProgressArea">
<h3 className="projectProgressStyling">
{project.completed}
</h3>
</div>
<div className="projectReturnButton">
<button
className="btnStyleDetailPage"
type="button"
onClick={() => { this.props.history.replace('/projects') }}>
Return to Project List
</button>
</div>
</div>
<div className="projectDetailImageArea">
<SRLWrapper>
<img className="projectImageStyling"
src={require("./placeholders/city.jpg")} alt={project.title} />
</SRLWrapper>
</div>
</div>
<Footer />
</div>
);
}
}
// Export Compoenent
export default ProjectDetail;
You can solve this by implementing a image carousel or iterating over the images array.
First of all you must guarantee that the pictures are properly set on a state (does not matter what type of component). Then, here is one way to show all of the images and solve the problem:
function ImageList(props) {
return (
props.images.map((pic, index) => {
return (
<img key={index} src={pic.src} alt="image" />
);
})
);
}
use map like this
{ data.map(project => { <div className="projectDetailMainContainer">
<div className="projectDetailGrid">
<div className="projectDetailArea">
<div className="projectNameArea">
<h1 className="projectNameStyling">
{project.title}
</h1>
</div>
<div className="projectAddress1Area">
<h2 className="projectAddress1Styling">
{project.address},
</h2>
</div>
<div className="projectAddress2Area">
<h2 className="projectAddress2Styling">
{project.address2}
</h2>
</div>
<div className="projectCityArea">
<h2 className="projectCityStyling">
{project.city} {project.zipcode}
</h2>
</div>
<div className="projectProgressArea">
<h3 className="projectProgressStyling">
{project.completed}
</h3>
</div>
<div className="projectReturnButton">
<button
className="btnStyleDetailPage"
type="button"
onClick={() => { this.props.history.replace('/projects') }}>
Return to Project List
</button>
</div>
</div>
<div className="projectDetailImageArea">
<SRLWrapper>
<img className="projectImageStyling"
src={require("./placeholders/city.jpg")}
alt={project.title} />
</SRLWrapper>
</div>
</div>
<Footer />
</div>
})}
for the images you can access them by index like this
{project.images[0].src}
{project.images[1].src}
{project.images[2].src}
example:
<img src={project.images[0].src} alt="image" />

React pass ref throw functional components in different levels

I would like to scroll to menu element in a page.
I have the menu component which is not a parent of components to which I would like to scroll.
I have found this post that describe a similar problem
Passing ref to a child We want the ref to be attached to a dom element, not to a react component. So when passing it to a child
component we can't name the prop ref.
const myRef = useRef(null)
return <ChildComp refProp={myRef}></ChildComp> } ```
Then attach the ref prop to a dom element. ```jsx const ChildComp =
(props) => {
return <div ref={props.refProp} /> } ```
Here's my app structure
Menu component:
const MenuApp = () => {
return (
<div>
<div className="desktop-menu">
<div className="menu-item a-propos">
<p className='button'>Me découvrir</p>
</div>
<div className="menu-item competences">
<p className='button'>Compétences </p>
</div>
<div className="menu-item experiences">
<p className='button'>Experiences</p>
</div>
<div className="menu-item formation">
<p className='button'>Formation </p>
</div>
</div>
</div>
)
}
The parent is app component
<div className="App">
<div className="hero">
<HeaderApp />
<ApprochApp />
</div>
<Apropos />
<Competences />
<Experiences />
<Formation />
<Recom />
<Contact />
<Footer />
</div >
I would like that mu menus scrolls to the react components in the main App component
So how can I passe the reference from the menu component to the app and use it in components to scroll ?
I do not understand your problem completely though. However, one thing I can see from your question is that you're not forwarding the ref properly.
What you need in this case is forwardRef.
Basically, what you need to do is to create the childComponent as something like this:
const childComponent = React.forwardRef(({...otherProps}, ref) => {
return (<><div ref={ref}>Component content </div></>)
})
Where you need to use the component all you need to do is this:
const parentComponent = () => {
const reveiwsRef = React.useRef("");
return (
<div>
<childComponent ref={reviewsRef} />
</div>
);
}
You can find more info about this on the react documentation: Forwarding-Refs
I have hope this helps though

Simplest way to use onClick to render <img> in React?

Im looking for a way to display an image when a button is toggled on. It seems like a simple enough task, and would help me greatly to understand how to do it. I have tried something like this, but it does not render anything.
This is the function that returns the svg image:
import dfElement from '../vectors/dfElement.svg';
function renderElement(){
return <img src={dfElement}/>
}
This is the class that calls the function to return svg:
class DF extends Component {
render() {
return (
<div >
<div >
<button onClick={this.renderElement}>df</button>
</div>
</div>
);
}
}
export default DF
I've used Functional Component with useState().
It's a simpler way to make a component.
ref >
https://en.reactjs.org/docs/hooks-intro.html
function App(){
const [toggle, setToggle] = React.useState(false);
return (
<div>
<button onClick={()=>setToggle( (prev) => (!prev) )}>Toggle!</button>
<br/>
{
toggle && <img src='https://2.imimg.com/data2/LQ/QV/MY-/teddy-small-size-500x500.jpg' />
}
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root" />

ReactJS SetState not rerendering

I have:
JobScreen
handleSetView(mode, e) {
this.setState({
view: mode
});
console.log(this.state.view)
}
render() {
return (
<div className="jobs-screen">
<div className="col-xs-12 col-sm-10 job-list"><JobList view={this.state.view} /></div>
<div className="col-xs-12 col-sm-2 panel-container">
<div className="right-panel pull-right"><RightPanel handleSetView={this.handleSetView} /></div>
...
)
}
RightPanel
render() {
return (
<div>
<div className="controls">
<span className="title">Views <img src="images\ajax-loader-bar.gif" width="24" id="loader" className={this.state.loading ? "pull-right fadeIn" : "pull-right fadeOut"}/></span>
<button onClick={this.props.handleSetView.bind(this, 'expanded')}><img src="/images/icons/32px/libreoffice.png" /></button>
<button onClick={this.props.handleSetView.bind(this, 'condensed')}><img src="/images/icons/32px/stack.png" /></button>
</div>
...
)}
JobList
render() {
var jobs = [];
this.state.jobs.forEach((job) => {
jobs.push(
<Job key={job.id} job={job} view={this.props.view} loading={this.state.loading} toggleTraderModal={this.props.toggleTraderModal} toggleOFTModal={this.props.toggleOFTModal}/>
);
});
return (
<div>
{jobs}
</div>
);
};
The problem is, is that the changing of the view state does not rerender any of the child elements.
How can I get this to work?
Not sure if it is the core of your problem, but:
handleSetView={this.handleSetView}
is wrong, because how js binds this. Use:
handleSetView={this.handleSetView.bind(this)}
instead.
Also,
this.setState({
view: mode
});
console.log(this.state.view)
seems strange; note that this.state is not modified right after you call setState, it may took some time while React dispatches the scheduled setState operation. Put that console.log into render to see when it is actually called.
Finally, make sure, your components do not implement shouldComponentUpdate lifecycle method (you are probably not doing this explicitly, but if your component extends some class other than React.Component this may happen)
this is in the context of the react Component so either pass the reference of this to you function handleSetView or bind this as mentioned by #Tomas

Categories

Resources