Home > Net >  rendering react links from JSON file
rendering react links from JSON file

Time:05-25

Is there a way to get react links from JSON file? for example from:

const data = [
        {
            id: 1,
            paragraph: `Some text <Link to="/main-page">main page</Link> some text.`
        },
        {
            id: 2,
            paragraph: `Some text <Link to="/main-page">main page</Link> some text.`
        },
        
    ];

const App = () => ( 
        {data.map((item) => (
            <div key={item.id}>
                <p dangerouslySetInnerHTML={{
                    __html: item.paragraph
                }}>
                </p>
            </div>
        ))}
);

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

dangerouslySetInnerHTML works only for HTML tags and is not helping in this case

CodePudding user response:

I don't fully understand what you are trying to accomplish but you can import

the json file change the data to an Object and use it

but first you need to install json-loader and load the data anywhere you will like it

   export default {
    "data" : "data"
    }

import someData from './someData' 

const arr = [someDta.json()];

return (<div>
            {arr.map(item => {
              {paragraph: `Some text <Link to="/main-page">{{item .data}}</Link> some text.`}   
            })} 

       </div>
)

CodePudding user response:

If there is no other way and this is the data you must process, you can use regular expression in order to extract this info from the text and then re-create the Link

let paragraph = 'Some text <Link to="/main-page">main page</Link> some text.'
console.log('Link text ==>', paragraph.match(/(?<=>)[^<] /)[0])
console.log('Link target ==>', paragraph.match(/(\S )=["']?((?:.(?!["']?\s (?:\S )=|[>"'])) .)["']?/)[2])

although, the best solution is the one Lissy93 noted.

  • Related