Search code examples
javascriptreactjsecmascript-6reduxreact-dom

How to convert React.DOM elements to JSX?


When it comes to React JSX code standards: How would I go about refactoring the following code bellow to JSX?

const ListContainer = (props) => React.DOM.table({ className: 'list-container' }, [
    React.DOM.thead({ key: 'firstName' }, React.DOM.tr({}, [
        React.DOM.th({ key: 'lastName' }, null, 'headshot'),
        React.DOM.th({ key: 'id' }, null, 'First Name'),
        React.DOM.th({ key: 'last-h' }, null, 'Last Name')
    ])),
    React.DOM.tbody({ key: 'tbody' }, props.personList.map((person, i) =>
        React.createElement(ListRow, { key: `person-${i}`, person })))
]);

Solution

  • See a demo at: CodePen

    Translated below:

    const ListContainer = props => (
        <table className="list-container">
            <thead>
                <th>
                    headshot
                </th>
                <th>
                    First Name
                </th>
                <th>
                    Last Name
                </th>
            </thead>
            <tbody>
                {
                    props.personList.map((person, i) => {
                        return <ListRow key={`person-${i}`} person={person} />
                    })
                }
            </tbody>
        </table>
    );
    

    Of course for the above you would need to use babel transpiler (let me know if you need more info on this).

    You can then use your const as follows in JSX:

    <ListContainer />