最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to render raw HTML content to React pass via props? - Stack Overflow

programmeradmin7浏览0评论

I'm trying to pass a variable in return of a ponent. Here is my code:

const Obj = (props) => {

    let { propId } = useParams();
    
    const [data, setData] = useState({ course: [] });

    useEffect(() => {
        (async () => {
            const result = await axios.get(
                '/' + propId
            ).catch(err => {
                console.error(err);
            });
            setData(result.data);
        })();
    }, [propId]);
    
    return (
        <Fragment key={propId}>
            <div>
                {data.htmlContent}
            </div>
        </Fragment>
    );
};

export default Obj;

At here it shows this:

<p>Lorem ipsum dolor sit amet</p>

How can I insert this html content to main content?

I'm trying to pass a variable in return of a ponent. Here is my code:

const Obj = (props) => {

    let { propId } = useParams();
    
    const [data, setData] = useState({ course: [] });

    useEffect(() => {
        (async () => {
            const result = await axios.get(
                'http://example./api/v1/' + propId
            ).catch(err => {
                console.error(err);
            });
            setData(result.data);
        })();
    }, [propId]);
    
    return (
        <Fragment key={propId}>
            <div>
                {data.htmlContent}
            </div>
        </Fragment>
    );
};

export default Obj;

At here it shows this:

<p>Lorem ipsum dolor sit amet</p>

How can I insert this html content to main content?

Share Improve this question edited Aug 25, 2020 at 20:16 Boussadjra Brahim 1 asked Aug 25, 2020 at 19:39 sundowatchsundowatch 3,1254 gold badges47 silver badges75 bronze badges 5
  • I actually get <p>Lorem ipsum dolor sit amet</p> – sundowatch Commented Aug 25, 2020 at 19:43
  • you passing html , it's not JSX. when you create html tags on react, it's actually a react elements, where is different from the html you get from the request. you need to convert it to a react element – zb22 Commented Aug 25, 2020 at 19:44
  • Then, how can I convert this to JSX? – sundowatch Commented Aug 25, 2020 at 19:44
  • stackoverflow./questions/40108843/… – Behrouz Pooladrak Commented Aug 25, 2020 at 20:10
  • you can use "html-to-react" library npmjs./package/html-to-react – zb22 Commented Aug 25, 2020 at 20:21
Add a ment  | 

1 Answer 1

Reset to default 6

Try the dangerouslySetInnerHTML attribute :

 <Fragment key={propId}>
            <div dangerouslySetInnerHTML={ { __html: data.htmlContent}} >
           
            </div>
        </Fragment>
发布评论

评论列表(0)

  1. 暂无评论